选择类排序法,是每一趟遍历从待排序记录中选出关键字最小的记录,放在已排好序的序列最后直至排完。常用的选择排序有两种,分别是直接选择排序和堆排序
1、直接选择排序
基本原理:直接选择排序,在第 i 趟选择排序是指通过 n-i 次关键字的比较,从n-i+1 个记录中选出关键字最小的记录,并和第 i 个记录交换,直到排序完
算法分析:无论序列初始状态如何,在第 i 趟排序中选出最小关键字的记录,需要做 n-i 次比较,所以总的比较次数为 O(n2)。直接选择排序是就地排序,是不稳定的
void selectSort(int a[], int n) {
int iTemp;
for (int i = 0; i < n; ++i) {
iTemp = i;
// search the min element and the index
for (int j = i + 1; j < n; ++j)
if (a[j] < a[iTemp])
iTemp = j;
if (iTemp != i) {
int t = a[i];
a[i] = a[iTemp];
a[iTemp] = t;
}
}
}
2、堆排序
基本原理:堆排序是指在排序过程中,将向量中存储的数据看成一颗完全二叉树,利用完全二叉树中双亲节点和孩子节点之间的内在关系,选择关键字最小的元素
算法分析:此算法的关键是构建堆,可以反复利用筛选的方式,自底向上把所有的子树调整为堆。首先建立初堆,并输出堆顶元素。调整剩余的记录,在重新生成堆,重复此操作
相关代码
/** heap sort **/
// build heap
void createHeap(int a[], int index, int n) {
int j, t;
while (2 * index + 1 < n) { // node index's right child in the range of n
j = 2 * index + 1;
if (j + 1 < n) {
if (a[j] < a[j + 1]) // if left child small than right child,then compare the right child
j++;
}
if (a[index] < a[j]) {
t = a[index];
a[index] = a[j];
a[j] = t;
index = j;
} else // compare left and right child,if heap does not be broken,then no necessary to adjust
break;
}
}
void heapSort(int a[],int n){
int iTemp;
for (int i = n/2-1; i >=0 ; --i)
createHeap(a,i,n);
for (int j = n-1; j >0 ; --j) {
iTemp = a[0] ;
a[0] = a[j];
a[j] = iTemp;
createHeap(a,0,j);
}
}

被折叠的 条评论
为什么被折叠?



