标签:
template <typename Comparable> void selectSort (vector<Comparable>&) {//找出按从小到大排序应排在第i个位置的记录并和第i个元素交换 for ( int i = 0; i < a.size()-1; ++i) { Comparable temp = a[i]; int tempIndex = i; for ( int j = i + 1; j < a.size(); ++j ) { if ( a[j] < temp ) { temp = a[j]; tempIndex = j; } } temp = a[i]; a[i] = a[tempIndex]; a[tempIndex] = temp; } }
二.堆排序
int leftChild ( int i ) { return 2 * i + 1; } template < typename Comparable > void adjust ( vector<Comparable> & a, int i, int n ) {//调整由元素i到n构成的堆 int child; Comparable temp; for ( temp = a[i]; leftChild(i) <= n; i = child) { //如果有右孩子,则取两个孩子中的最大值 child = leftChild ( i ); if( child != n && a[ child ] < a[ child + 1] ) child++; if( temp < a[ child ] ) {//往下移 a[ i ] = a[ child ]; } else break; } //找到插入位置,进行插入 a[ i ] = temp; } template < typename Comparable > void heapSort ( vector<Comparable> & a) {//对下标为0到a.size()-1的元素进行排序 for ( int i = a.size() / 2 ; i >= 0; i-- ) adjust(a, i, a.size()-1); for ( int j = a.size() - 1; j > 0; j-- ) { Comparable temp = a[j];//交换堆顶和最后一个元素 a[j] = a[0]; a[0] = temp; adjust(a,0,j-1);//重新调整堆,最后第j个元素用来存储堆顶, //不用再考虑. } }
标签:
原文地址:http://www.cnblogs.com/happygirl-zjj/p/4649061.html