voidmerge(int arr[], int left[], int leftSize, int right[], int rightSize){ int i = 0, j = 0, k = 0; while (i < leftSize && j < rightSize) { if (left[i] < right[j]) { arr[k++] = left[i++]; } else { arr[k++] = right[j++]; } } while (i < leftSize) { arr[k++] = left[i++]; } while (j < rightSize) { arr[k++] = right[j++]; } }
voidmergeSort(int arr[], int n){ if (n < 2) return; int mid = n / 2; int left[mid]; int right[n - mid]; for (int i = 0; i < mid; i++) { left[i] = arr[i]; } for (int i = mid; i < n; i++) { right[i - mid] = arr[i]; } mergeSort(left, mid); mergeSort(right, n - mid); merge(arr, left, mid, right, n - mid); }
intpartition(int arr[], int low, int high){ int pivot = arr[high]; int i = low - 1; for (int j = low; j <= high - 1; j++) { if (arr[j] < pivot) { i++; int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } int temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp; return i + 1; }
voidquickSort(int arr[], int low, int high){ if (low < high) { int pi = partition(arr, low, high); quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } }
voidshellSort(int arr[], int n){ for (int gap = n / 2; gap > 0; gap /= 2) { for (int i = gap; i < n; i++) { int temp = arr[i]; int j; for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) { arr[j] = arr[j - gap]; } arr[j] = temp; } } }
voidheapify(int arr[], int n, int i){ int largest = i; int left = 2 * i + 1; int right = 2 * i + 2; if (left < n && arr[left] > arr[largest]) { largest = left; } if (right < n && arr[right] > arr[largest]) { largest = right; } if (largest != i) { int temp = arr[i]; arr[i] = arr[largest]; arr[largest] = temp; heapify(arr, n, largest); } }
voidheapSort(int arr[], int n){ for (int i = n / 2 - 1; i >= 0; i--) { heapify(arr, n, i); } for (int i = n - 1; i >= 0; i--) { int temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; heapify(arr, i, 0); } }
计数排序(Counting Sort)
计数排序是一种非比较排序算法,它通过计算数列中每个数出现的次数来排序。它的时间复杂度为 O (n),因此在数据范围较小的情况下可以使用计数排序。
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
voidcountingSort(int arr[], int n, int maxValue){ int counts[maxValue + 1]; for (int i = 0; i <= maxValue; i++) { counts[i] = 0; } for (int i = 0; i < n; i++) { counts[arr[i]]++; } for (int i = 0, j = 0; i <= maxValue; i++) { while (counts[i]-- > 0) { arr[j++] = i; } } }