Adam Barker <adam@NO_SP_AM> wrote:
Despite looking awful, this method is actually far far quicker than
Array.Sort() !
While it may be quicker to do a bubble sort for a few items, it gets
*much* slower over larger arrays.
Try the following program with different sizes. On my box, an array
with 100,000 elements took 0.06s to sort with Array.Sort, and 13.8s to
sort with the bubble sort. Of course, the time taken will depend on the
actual data (a bubble sort is very quick on data which is already
sorted).
using System;
class Test
{
static void Main(string[] args)
{
int size = int.Parse(args[0]);
int[] testData = new int[size];
Random rng = new Random();
for (int i=0; i < size; i++)
{
testData[i] = rng.Next(size);
}
int[] testData2 = (int[]) testData.Clone();
DateTime start = DateTime.Now;
Array.Sort(testData);
DateTime end = DateTime.Now;
Console.WriteLine ("Array.Sort: {0}", end-start);
start = DateTime.Now;
BubbleSort(testData2);
end = DateTime.Now;
Console.WriteLine ("BubbleSort: {0}", end-start);
}
static void BubbleSort (int[] array)
{
int length = array.GetLength(0)-1;
for (int i=0;i<length;)
{
if (array[i] > array[i+1])
{
int a=array[i+1];
array[i+1]=array[i];
array[i]=a;
if (i>0)
i--;
}
else
i++;
}
}
}
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too