//If any child is bigger than parent, //then we swap it and do adjust for child again to make sure meet max heap definition if( max_index != parentindex ) { swap_time++; swap(sortarray[max_index], sortarray[parentindex]); heapAdjust(sortarray, max_index, length); } }
//通过初试数据构建最大堆 voidbuildingHeap(int* sortarray) { for( int i = int(intArraySize(sortarray)/2) - 1; i >= 0; i--) { //1.2 Adjust heap //Make sure meet max heap definition //Max Heap definition: // (k(i) >= k(2i) && k(i) >= k(2i+1)) (1 <= i <= n/2) heapAdjust(sortarray, i, intArraySize(sortarray)); } }
//1. Build max heap // 1.1 Init heap //Assume we construct max heap buildingHeap(sortarray); //2. Sort heap //这里花O(n),跟数据数量有关 for( int i = intArraySize(sortarray) - 1; i > 0; i-- ) { //swap first element and last element //do adjust heap process again to make sure the new array are still max heap swap(sortarray[i],sortarray[0]); //Due to we already building max heap before, //so we just need to adjust for index 0 after we swap first and last element heapAdjust(sortarray, 0, i); } }
intpartition(int* sortarray, int l, int r) { //choose pivot int pivot = sortarray[r]; int i = l; for( int j = l; j < r; j++ ) { time_complexity++; if( sortarray[j] <= pivot ) { swap(sortarray[i],sortarray[j]); i++; } } swap(sortarray[i], sortarray[r]); return i; }
voidquicksort(int* sortarray, int low, int high, bool benableoptimize) { //partition //Here we use last element of array as pivot //recursion //Pivot chosen to optimize quicksort // median-of-three int pivotpos; int middlepos = (high + 1) / 2; if( benableoptimize ) { if( sortarray[low] > sortarray[middlepos] ) { swap(sortarray[low],sortarray[middlepos]); }
voidmerge(vector& sortarray, int start, int middle, int end) { int left_size = middle - start + 1; int right_size = end - middle; vector left; vector right; for( int i = 0; i < left_size; i++ ) { left.push_back(sortarray[start + i]); }
int k = 0; int l = 0; int index = start; //The worst condition is compare n * log(n) - n + 1 //The best condition is compare n * log(n) / 2 while( k < left_size && l < right_size ) { if( left[k] < right[l] ) { sortarray[index] = left[k]; k++; } else { sortarray[index] = right[l]; l++; } index++; }