/****************************************** 不稳定的排序算法: 选择排序(selection sort)— O(n^2) 希尔排序(shell sort)— O(nlog n) 如果使用最佳的现在版本 堆排序(heapsort)— O(nlog n) 快速排序(quicksort)— O(nlog n) 期望时间,O(n^2) 最坏情况; 对于大的、乱数列表一般相信是最快的已知排序 *******************************************/ //插入排序 void InsertionSort( int *arr, int length ) { if ( arr == NULL || length < 2 ) return; for( int index = 1; index < length; ++index ) { int key = arr[index]; int j = index - 1; for( ; j >= 0 && key < arr[j]; --j ) arr[ j+1 ] = arr[j]; arr[j+1] = key; } } //冒泡排序 void BubbleSort( int *arr, int length ) { if ( arr == NULL || length < 2 ) return; bool IsChanged = true; for ( int i = 0; i < length; ++i ) { if ( IsChanged == false ) return; for ( int j = length - 1; j > i; --j ) { IsChanged = false; if ( arr[j] < arr[j-1] ) { swap( arr[j], arr[j-1] ); IsChanged = true; } } } } //维基百科的方法,划分“增量”以后,不是对每一个子数组进行插入排序, //而是对整个数组进行扫描,进行整个的插入排序 //希尔排序 void ShellSort(int *data, size_t size) { for (int gap = size / 2; gap > 0; gap /= 2) for ( int i = gap; i < size; ++i ) { int key = data[i]; int j = 0; for( j = i -gap; j >= 0 && data[j] > key; j = j - gap ) { data[j+gap] = data[j]; } data[j+gap] = key; } } void Merge( int arr[], int nBegin, int nMid, int nEnd ) { int lengthL = nMid - nBegin + 1; int lengthR = nEnd -nMid; int *L = new int [ lengthL +1 ]; int *R = new int [ lengthR + 1 ]; for( int i = 0; i < lengthL; ++i ) L[i] = arr[ nBegin + i ]; for( int i = 0; i < lengthR; ++i ) R[i] = arr[ nMid + i + 1 ]; L[ lengthL ] = INT_MAX; R[ lengthR ] = INT_MAX; int indexL = 0; int indexR = 0; for ( int i = nBegin; i <= nEnd; ++i ) { if ( L[ indexL ] <= R[ indexR ] ) { arr[ i ] = L[ indexL ]; ++indexL; } else { arr[ i ] = R[ indexR ]; ++indexR; } } delete [] L; delete [] R; } //归并排序 void MergeSort( int arr[], int start, int end ) { if ( end > start ) { int mid = (end + start) / 2; MergeSort( arr, start, mid); MergeSort( arr, mid + 1,end ); Merge( arr,start, mid,end ); } } int Partition ( int data[], int start, int end ) { int index = data[end]; int i = start - 1; for ( int j = start ; j < end ; ++j ) { if ( data[j] <= index ) { ++i; swap( data[i], data[j] ); } } swap( data[i+1], data[end] ); return i+1; } //快速排序 void QuickSort( int data[], int start, int end ) { if ( start < end ) { int mid = Partition ( data, start,end ); QuickSort( data, start, mid -1 ); QuickSort( data, mid + 1, end ); } }