小仙女讲软考(四):选择排序

如果说插入排序是这样:

那选择排序就是这样:

选择排序分为简单选择排序和堆排序。这两个都较简单。

简单选择

定义:每一趟在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;
}

 

小结

选择排序是冒泡排序的优化

评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

卡夫卡的熊kfk

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值