今天说说选择排序。
首先和昨天写到的冒泡排序做下比较,冒泡排序是两两比较前者大就交换的排序,很可能交换的次数极多,要知道交换耗费的性能是要比比较耗费的性能高的。于是选择排序在交换的次数上进行了优化。从数组开始每次取一个数与后面的数比较,存下大数的值和索引位,在比较完一次后进行交换。交换总次数相对稳定。
using System;
/// <summary>
/// 选择排序
/// 思想是相对于冒泡来说较少交换次数,交换毕竟比比较费时
/// </summary>
namespace test
{
class MainClass
{
public static void Main (string[] args)
{
int [] arr = {3, 2, 67, 5, 4, 1, 9};
SelectSort (arr);
foreach (int i in arr) {
Console.WriteLine (i);
}
}
//简单选额排序
private static void SelectSort (int [] arr) {
int min, temp, tempIndex; //最小值,交换中间值,每轮换得的最小值索引
for (int i = 0; i < arr.Length; i++) {
min = arr [i];
tempIndex = i;
for (int j = i + 1; j < arr.Length; j++) { //比较得到最小值和其索引值
if (arr [j] < min) {
min = arr [j];
tempIndex = j;
}
}
//交换
temp = arr [i];
arr [i] = arr [tempIndex];
arr [tempIndex] = temp;
}
}
}
}