C#实现:选择排序
直接选择排序
直接选择排序是一种选择排序,是一种不稳定的排序,时间复杂度为 O(n^2)。
基本思想
每一趟从待排序的数据元素中选出最小的一个元素,顺序放在已排好序的数列的最后,直到全部待排序的数据元素排完。
40 10 20 15
①{10} 40 20 15 将第一个元素 40 和无序区中最小的 10 交换
②{10 15} 20 40 将第二个元素 40 和无序区中最小的 15 交换
③{10 15 20} 40 将第三个元素 20 已是无序区中最小不用交换
④{10 15 20 40} 到倒数第二个元素结束
public void sort(int[] data)
{
int key, index;
for (int i = 0; i < data.Length - 1; i++)
{
key = data[i];
index = i;
//选择最小的元素
for (int j = i + 1; j < data.Length; j++)
{
if (data[j] < key)
{
key = data[j];
index = j;
}
}
//交换
data[index] = data[i];
data[i] = key;
}
}
{
int key, index;
for (int i = 0; i < data.Length - 1; i++)
{
key = data[i];
index = i;
//选择最小的元素
for (int j = i + 1; j < data.Length; j++)
{
if (data[j] < key)
{
key = data[j];
index = j;
}
}
//交换
data[index] = data[i];
data[i] = key;
}
}
本贴子以“现状”提供且没有任何担保,同时也没有授予任何权利
This posting is provided "AS IS" with no warranties, and confers no rights.
This posting is provided "AS IS" with no warranties, and confers no rights.
浙公网安备 33010602011771号