如果说插入排序是这样:
那选择排序就是这样:
选择排序分为简单选择排序和堆排序。这两个都较简单。
简单选择
定义:每一趟在n-i+1(i=1,2,…n-1)个记录中选取关键字最小的记录作为有序序列中第i个记录。
特点:遍历;交换
图解:
[图解1]
[图解2]
代码实现:
public void SimpleSelectSort(int[] array)
{
int tmp=0;
int t=0;//最小数标记
for(int i=0; i<array.Length; i++)
{
t=i;
for(int j=i+1; j<array.Length; j++)
{
if(array[t]>array[j])
{
t=j;
}
}
tmp=array[i];
array[i]=array[t];
array[t]=tmp;
堆排序
定义:
利用堆这种数据结构所设计的一种排序算法。其可以利用数组的特点快速定位指定索引的元素。堆是完全二叉树,分为大根堆和小根堆。
据说此排序在面试中出现频率很高。
特点:堆;数组
实现步骤:(以大根堆为例)
1将本来无序堆调整为有序的大根堆
调整为有序:
2取出堆顶元素,将末尾元素补到堆顶
3重复步骤1
代码实现
///<summary>
///构建堆
///</summary>
static void HeapAdjust(List<int> list,int parent,int length)
{
int temp=list[parent];
int child=2*parent+1;
while(child<length)
{
if(child+1<length&&list[child]<list[child+1])child++;
if(temp>=list[child])
break;
list[parent]=list[child];
parent=child;
child=2*parent+1;
}
list[parent]=temp;
}
///<summary>
///堆排序
///</summary>
public static List<int> HeapSort(List<int> list,int top)
{
List<int> topNode=new List<int>();
for(int i=list.Count/2-1;i>=0;i--)
{
HeapAdjust(list,i,list.Count);
}
for(int i=list.Count-1;i>=list.Count-top;i--)
{
int temp=list[0];
list[0]=list[i];
list[i]=temp;
topNode.Add(temp);
HeapAdjust(list,0,i);
}
return topNode;
}
小结
选择排序是冒泡排序的优化