C#选择排序
C#选择排序一、选择排序基本思想
每一趟从待排序的数据元素中选出最小(或最大)的一个元素,顺序放在已排好序的数列的最后,直到全部待排序的数据元素排完。
/// <summary>
/// selection sort
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="array"></param>
/// <param name="left"></param>
/// <param name="right"></param>
public static void SelectionSort<T>(T[] array) where T : IComparable
{
int length = array.Length;
for (int i = 0; i < length; i++)
{
T min = array[i];
int minIndex = i ;
for (int j = i+1; j < length; j++)
{
if (min.CompareTo(array[j])>0)
{
min = array[j];
minIndex = j;
}
}
if (minIndex != i)
{
array[minIndex] = array[i];
array[i] = min;
}
}
}
测试代码
int[] array = new int[] {43,23,80,15,789,27,90,69,66,158,45,32,1,22,77,66,44};
Console.WriteLine("before selection sort");
foreach (int i in array)
{
Console.Write(i+"->");
}
Console.WriteLine();
SortHelper.SelectionSort<int>(array);
Console.WriteLine("after selection sort");
foreach (int i in array)
{
Console.Write(i + "->");
}
Console.WriteLine();
Console.Read();
六、C# 选择排序排序过程
初始关键字 [49 38 65 97 76 13 27 49]