选择排序是一种简单直观的排序算法。它的工作原理如下。
首先在未排序列中找到最小的元素,存放到排序序列的起始位置。然后,在从剩余未排序元素中继续寻找最小的元素,放到排序序列末尾。以此类推,直到所有元素均排序完毕。
class SelectSorter
{
private static int[] myArray;
private static int arraySize;
public static void Sort(int[] a)
{
myArray = a;
arraySize = myArray.Length;
SelectSort(myArray);
}
public static void SelectSort(int[] myArray)
{
int i, j, smallest;
for(i=0;i<myArray.Length-1;i++) //数据起始位置,从0到倒数第二个数据 {
smallest = i; //记录最小数的下标
for (j = i + 1; j < myArray.Length; j++) //在剩下的数据中寻找最小数 {
if (myArray[j] < myArray[smallest]) {
smallest = j; //如果有比它更小的,记录下标 }
}
Swap(ref myArray[i], ref myArray[smallest]); //将最小数据和未排序的第一个数交换 }
}
private static void Swap(ref int left, ref int right)
{
int temp;
temp = left;
left = right;
right = temp;
}
static void Main(string[] args)
{
int[] a = new int[] { 4, 2, 1, 6, 3 };
SelectSorter.Sort(a);
for (int i = 0; i < a.Length; i++)
{
System.Console.WriteLine(a[i]);
}
System.Console.Read();
}
}