Sorting algorithms/Bubble sort: Difference between revisions

Content added Content deleted
(add C# radix sort)
Line 415: Line 415:
</pre>
</pre>


=={{header|C sharp|C#}}==
{{works with|C sharp|C#|3.0+}}
<lang csharp>using System;
<lang csharp>using System;
using System.Collections.Generic;


namespace RadixSort
namespace RosettaCode.BubbleSort
{
{
class Program
public static class BubbleSortMethods
{
{
//The "this" keyword before the method parameter identifies this as a C# extension
static void Sort(int[] old)
//method, which can be called using instance method syntax on any generic list,
//without having to modify the generic List<T> code provided by the .NET framework.
public static void BubbleSort<T>(this List<T> list) where T : IComparable
{
{
int i, j;
bool madeChanges;
int[] tmp = new int[old.Length];
int itemCount = list.Count;
for (int shift = 31; shift > -1; --shift)
do
{
{
j = 0;
madeChanges = false;
for (i = 0; i < old.Length; ++i)
itemCount--;
for (int i = 0; i < itemCount; i++)
{
{
bool move = (old[i] << shift) >= 0;
if (list[i].CompareTo(list[i + 1]) > 0)
if (shift == 0 ? !move : move) // shift the 0's to old's head
{
old[i-j] = old[i];
T temp = list[i + 1];
else // move the 1's to tmp
list[i + 1] = list[i];
tmp[j++] = old[i];
list[i] = temp;
madeChanges = true;
}
}
}
Array.Copy(tmp, 0, old, old.Length-j, j);
} while (madeChanges);
}
}
}
}
static void Main(string[] args)

//A short test program to demonstrate the BubbleSort. The compiler will change the
//call to testList.BubbleSort() into one to BubbleSortMethods.BubbleSort<T>(testList).
class Program
{
static void Main()
{
{
int[] old = new int[] { 2, 5, 1, -3, 4 };
List<int> testList = new List<int> { 3, 7, 3, 2, 1, -4, 10, 12, 4 };
Console.WriteLine(string.Join(", ", old));
testList.BubbleSort();
Sort(old);
foreach (var t in testList) Console.Write(t + " ");
Console.WriteLine(string.Join(", ", old));
Console.Read();
}
}
}
}