1、快速排序
#include <iostream> using namespace std; const int N = 1e5 + 10; int n, q[N]; void qksort(int q[], int l, int r) { if (l >= r) return; int x = q[l], i = l - 1, j = r + 1; while (i < j) { do i++; while (q[i] < x); do j--; while (q[j] > x); if (i < j) swap(q[i], q[j]); } qksort(q, l, j), qksort(q, j + 1, r); } int main() { scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &q[i]); qksort(q, 0, n - 1); for (int i = 0; i < n; i++) printf("%d ", q[i]); return 0; }
2、归并排序
#include <iostream> using namespace std; const int N = 1e5 + 10; int n, q[N], tmp[N]; void mergeSort(int q[], int l, int r) { if (l >= r) return; int mid = (l + r) >> 1; mergeSort(q, l, mid), mergeSort(q, mid + 1, r); int k = 0, i = l, j = mid + 1; while (i <= mid && j <= r) { if (q[i] <= q[j]) tmp[k++] = q[i++]; else tmp[k++] = q[j++]; } while (i <= mid) tmp[k++] = q[i++]; while (j <= r) tmp[k++] = q[j++]; for (i = l, j = 0; i <= r; i++, j++) q[i] = tmp[j]; } int main() { scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &q[i]); mergeSort(q, 0, n - 1); for (int i = 0; i < n; i++) printf("%d ", q[i]); return 0; }
标签:mergeSort,归并,int,qksort,mid,while,算法,排序 From: https://www.cnblogs.com/karinto/p/17707223.html