各种排序实现
有序插入排序:时间复杂度O(n^2),它是稳定的。
|
template< typename RecType > void HalfInsertSort( RecType R[], int n ) { int low, high, m = 0; int i, j = 0;
for( i = 2; i <= length; ++i ) { R[0] = R[i]; low = 1; high = i - 1;
while( low <= high ) { m = ( low + high ) / 2; if( R[0] < R[m] ) { high = m - 1; } else { low = m + 1; } }
for( j = i - 1; j >= high + 1; --j ) { R[j+1] = R[j]; } R[high+1] = R[0]; } }
|
Shell排序/希尔排序:时间复杂度为O(nLog2n),它不稳定的。
取一个小于N的整数的d1做为增量,将表分成(N/d1)+1个组,然后再各组内进行直接插入排序,然后取第2个增量d2,要求d2 < d1,重复上述分组排序,直到dt = 1为止,此时所有记录就等于将所有记录放在同一组进行插入排序。
|
template< typename RecType > void ShellSort( RecType R[], int n ) { int i, j, d = n / 2; RecType temp;
while( d > 0 ) { for( i = d; i < n; ++i ) { j = i - d; while( j >= 0 ) { if( R[j] > R[j+d] ) { temp = R[j]; R[j] = R[j+d]; R[j+d] = temp; j -= d; } else { j -= 1; } } } d = d / 2; } } |
冒泡排序:时间复杂度O(n^2),它是稳定的。
从头结点N0开始,比较N0和N1,将较大的数放置N1处,然后N1和N2比较,较大的放置N2处,循环一次,则获得最大数放置在Nn-1处,然后再从N0开始到Nn-1个结点进行比较循环,最后一直到所有记录有序为止。
|
template< typename RecType > void BubbleSort( RecType R[], int n ) { int i, j = 0; RecType temp;
for( i = 0; j < n - 1; ++i ) { for( j = n - 1; j > i; --j ) { if( R[j] < R[j-1] ) { temp = R[j]; R[j] = R[j-1]; R[j-1] = temp; } } } } |
快速排序:时间复杂度为O( nLog2n ) ,它是不稳定的。
随机从数组中取一个记录为K,该值作为标准值,将数组分割为两部分,第一部分元素均小于或等于K,第二部分记录均大于或等于K,并将K填充到两个队列之间,这被称为一次快速排序。之后,对两部分内部数据重复进行随机选值2次分割,直至每个子序列只有一个记录为止。
|
template< typename RecType > void QuickSort( RecType R[], int s, int t ) { int i = s, j = t; RecType temp; if( i < j ) { temp = R[s]; while( i != j ) { while( j > i && R[j] > temp ) { j--; } if( i < j ) { R[i] = R[j]; ++i; } while( i < j && R[i] < temp ) { ++i; } if( i < j ) { R[j] = R[i]; j--; } } }
R[i] = temp; QuickSort( R, s, i - 1 ); QuickSort( R, i + 1, t ); } |
选择排序:时间复杂度O(n^2),它是不稳定的。
|
template< typename RecType > void SelectSort( RecType R[], int n ) { int i,j,k = 0; RecType temp; for( i = 0; i < n - 1; ++i ) { k = i; for( j = i + 1; j < n; ++j ) { if( R[j] < R[k] ) { k = j; } if( k != i ) { temp = R[i]; R[i] = R[k]; R[k] = temp; } } } } |
堆排序时一个树形选择排序,它的时间复杂度是O(nLog2n),它是不稳定的。
|
template< typename RecType > void HeapSort( RecType R[], int n ) { int i = 0; RecType temp; for( i = n / 2; i >= 1; --i ) { sift( R, i, n ); } for( i = n; i >= 2; --i ) { temp = R[1]; R[1] = R[i]; R[i] = temp; sift( R, 1, i-1 ); } } |
其他还有归并排序,基数排序等。

浙公网安备 33010602011771号