Jan 15, 2010

C# BubbleSort routine

So I wrote the first version (not optimized) in 5 minutes. For the optimization it took another 5 minutes.
This algorithm is O(n2) and as Knuth puts it, "...bubble sort seems to have nothing to recommend it, except a catchy name".

/// <summary>
/// Optimized version of BubbleSort that parses one less item each iteration
/// </summary>
public static class BubbleSort
{
public static int[] Sort(int[] input)
{
int temp, count = input.Length - 1;

while (count > 0)
{
for (int i = 0; i < count; i++)
{
if (input[i] > input[i + 1])
{
temp = input[i + 1];
input[i + 1] = input[i];
input[i] = temp;
}
}
count--;
}
return input;
}
}

There is also this interesting BubbleSort question on stackoverflow

No comments:

Post a Comment