voidSwap(int i, int j) { int val = nums[j]; nums[j] = nums[i]; nums[i] = nums[j]; }
/******************** 快排 ********************/ intPartition(int first, int last) { int pval = nums[first]; while (first < last) { while (first < last && pval <= nums[last]) --last; nums[first] = nums[last]; while (first < last && nums[first] <= pval) ++first; nums[last] = nums[first]; } nums[first] = pval; return first; }
voidQSort(int beg, int end) { if (beg + 1 < end) { int pivot = Partition(beg, end - 1); QSort(beg, pivot); QSort(pivot + 1, end); } }
/******************** 归并 ********************/ voidMerge(int beg, int mid, int end) { constint len = end - beg; int arr[len]; int i = beg, j = mid, k = 0; while (i < mid && j < end) { if (nums[i] <= nums[j]) arr[k++] = nums[i++]; else arr[k++] = nums[j++]; } while (i < mid) arr[k++] = nums[i++]; while (j < end) arr[k++] = nums[j++]; for (i = 0, j = beg; i < len; ++i, ++j) nums[j] = arr[i]; }
voidMergeSort(int beg, int end) { if (beg + 1 < end) { int mid = (beg + end) / 2; MergeSort(beg, mid); MergeSort(mid, end); Merge(beg, mid, end); } }
/******************** 堆排序 ********************/
intParent(int i) { return (i + 1) / 2 - 1; }
intLeft(int i) { return (i + 1) * 2 - 1; }
voidAdjustTop(int top, int len) { int topVal = nums[top]; for (int child; Left(top) < len; top = child) { child = Left(top); if (child + 1 < len && nums[child + 1] > nums[child]) ++child; if (topVal < nums[child]) nums[top] = nums[child]; else break; } nums[top] = topVal; }
voidHeapSort(int len) { int last = len - 1; for (int i = Parent(last); i >= 0; --i) AdjustTop(i, len); for (int last = len - 1; last > 0; --last) { Swap(0, last); AdjustTop(0, last); } }
/******************** 希尔 ********************/ voidShellSort(int len) { for (int gap = len / 2; gap > 0; gap /= 2) { for (int i = gap; i < len; ++i) { int lastV = nums[i], j; for (j = i; j >= gap && lastV < nums[j-gap]; j -= gap) nums[j] = nums[j-gap]; nums[j] = lastV; } } }
/******************** 插入 ********************/ voidInsertionSort(int len) { for (int i = 1; i < len; ++i) { int lastV = nums[i], j; for (j = i; j > 0 && lastV < nums[j-1]; --j) nums[j] = nums[j-1]; nums[j] = lastV; } }
intmain() { //while (cin >> n) { // for (int i = 0; i < n; ++i) // cin >> nums[i]; n = 9; int arr[9] = {1, 3, 4, 2, 0, 8, 4, 2, 7}; for (int i = 0; i < n; ++i) nums[i] = arr[i]; //QSort(0, n); //MergeSort(0, n); HeapSort(n); //InsertionSort(n); //ShellSort(n); cout << nums[n-1] << endl; for (int i = 0; i < (n - 1); ++i) { if (i != 0) cout << " "; cout << nums[i]; } if (n == 1) cout << -1; cout << endl; } return0; }