for (int i = 1; i < data.Count; i++)
{
int j = i;
while (j > 0)
{
if (numarray[j - 1] > numarray[j])
{
int temp = numarray[j - 1];
numarray[j - 1] = numarray[j];
numarray[j] = temp;
j--;
}
else
break;
}
}
Can someone help me identify what is the sorting algorithm of the above code? I know that bubble sort is not very efficient. If I am to use insertion sort algorithm instead, how can I improve the above code. Thankyou!
Just do this:
.NET has a default sort solution for arrays. Array.Sort. By default, .NET implements a Quicksort algorithm which sorts between O(n) and O(n log n). (this is much faster than a bubble sort).
You can use it by doing
Array.Sort(your_array)
, or if you need something more complicated (like sorting objects, or sorting in reverse), there is an overload which takes in an IComparer object.the most efficient way should be
Array.Sort(data);
which uses quicksortsome other sorting algorithms:
BubbleSort
InsertionSort
HeapSort
QuickSort
StoogeSort
SelectionSort
CocktailSort
GnomeSort
ShellSort