选择排序(Selection Sort)

选择排序(Selection Sort)是说,每次从数列中找出一个最小的数放到最前面来,再从剩下的n-1个数中选择一个最小的,不断做下去。
比如班上的MM搞选美活动,有人叫我给所有MM排个名。我们通常会用选择排序,即先找出自己认为最漂亮的,然后找第二漂亮的,然后找第三漂亮的,不断找剩下的人中最满意的。

C++代码如下

template  < class  Record >
void  Sortable_list < Record > ::selection_sort()
/*
Post: The entries of the Sortable_list have been rearranged so that
      the keys in all the entries are sorted into nondecreasing order.
Uses: max_key, swap.
*/

{
   
for (int position = count - 1; position > 0; position--{
      
int max = max_key(0, position);
      swap(max, position);
   }

}



template 
< class  Record >
int  Sortable_list < Record > ::max_key( int  low,  int  high)
/*
Pre:  low and high are valid positions in the Sortable_list and low <= high.
Post: The position of the entry between low and high with the largest
      key is returned.
Uses: The class Record, the contiguous List implementation.
*/

{
   
int largest, current;
   largest 
= low;
   
for (current = low + 1; current <= high; current++)
      
if (entry[largest] < entry[current])
         largest 
= current;
   
return largest;
}



template 
< class  Record >
void  Sortable_list < Record > ::swap( int  low,  int  high)
/*
Pre:  low and high are valid positions in the Sortable_list.
Post: The entry at position low is swapped with the entry at position high.
Uses: The contiguous List implementation.
*/

{
   Record temp;
   temp 
= entry[low];
   entry[low] 
= entry[high];
   entry[high] 
= temp;
}


/*其中Sortable_list是一个连续存储结构的list, 数据成员是List_entry entry[max_list];   List_entry是模版参数. max_list是常量*/


选择排序算法需要的比较次数是(n-1)+(n-2)+…+1=(1/2)n(n-1)=O(n^2),
需要的赋值次数是3n+O(1)..
优点正是是数据移动次数比较少,当数据采用连续存储方式,而且数据域比较大,数据移动对时间复杂度的贡献占较大比例时, 选择排序比较有用。
选择排序通过每一次移动至少把一个元素移动它的最终位置, 从而使使数据移动最少化..因为一旦某个元素已经在它的正确的位置,它将不会再移动.因此至多需要n-1次数据交换..
注意:选择排序是不稳定的. 所谓排序算法的稳定性是指:如果待排序的序列中有多个关键字相等的记录,假如经过这个算法排序之后,这些记录之间的相对顺序没有发生变化的话,那么这个排序算法是稳定的。 否则,这个算法是不稳定的。 一般来说排序过程中涉及两个记录进行交换的排序方法是不稳定的。



width="728" scrolling="no" height="90" frameborder="0" align="middle" src="http://kofreestyler.googlepages.com/csdnGGad.htm" marginheight="0" marginwidth="0">
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值