摘自Acwing
归并排序
1 #include <iostream> 2 using namespace std; 3 4 const int N = 1e5 + 10; 5 6 int n; 7 int q[N], tmp[N]; 8 void merge_sort(int q[], int l, int r) 9 { 10 if (l >= r) 11 return; 12 int mid = l + r >> 1; 13 merge_sort(q, l, mid), merge_sort(q, mid + 1, r); // recurse until 14 15 int k = 0, i = l, j = mid + 1; 16 while (i <= mid && j <= r) // two pointer 17 { 18 if (q[i] <= q[j]) 19 tmp[k++] = q[i++]; 20 else 21 tmp[k++] = q[j++]; 22 } 23 while (i <= mid) // remaining of left part 24 tmp[k++] = q[i++]; 25 while (j <= r) 26 tmp[k++] = q[j++]; // remaining of right part 27 for (i = l, j = 0; i <= r; i++, j++) // place them in the correct location 28 q[i] = tmp[j]; 29 } 30 int main() 31 { 32 scanf("%d", &n); 33 for (int i = 0; i < n; ++i) 34 scanf("%d", &q[i]); 35 merge_sort(q, 0, n - 1); 36 for (int i = 0; i < n; ++i) 37 printf("%d ", q[i]); 38 return 0; 39 }
N:最大数组长度(+10防止溢出)
n: 数组长度
q:原未排序数组 -> 排好序数组
tmp: 当前分离的两部分通过双指针找到的排好序的数组(类似选择排序)
每次得到tmp之后要把它放到正确的q的位置,所以加了26 - 27行
快速排序
1 #include <iostream> 2 using namespace std; 3 const int N = 1e5 + 10; 4 5 int n; 6 int q[N]; 7 8 void quick_sort(int q[], int l, int r) 9 { 10 if (l >= r) 11 return; 12 int x = q[(l + r) / 2], i = l - 1, j = r + 1; 13 while (i < j) 14 { 15 while (q[++i] < x); 16 while (q[--j] > x); 17 if (i < j) swap(q[i], q[j]); 18 } 19 quick_sort(q, l, j); 20 quick_sort(q, j + 1, r); 21 } 22 23 int main() 24 { 25 scanf("%d", &n); 26 for (int i = 0; i < n; ++ i) 27 scanf("%d", &q[i]); 28 quick_sort(q, 0, n - 1); 29 for (int i = 0; i < n; ++ i) 30 printf("%d ", q[i]); 31 return 0; 32 }
N:最大数组长度(+10防止溢出)
n: 数组长度
q:原未排序数组 -> 排好序数组
x:partition point
i和j:最左和最右的指针(类似selection sort)
与merge sort不同的是先排序再递归,首先使用双指针把小于x的和大于x的放在x的左边和右边(一样的既在左边也可以在右边,所以算法不稳定)
partition的位置既可以是最左边,右边,中间,也可以是随机的,平均的是见复杂度是O(n)
原文地址:https://www.cnblogs.com/goldenticket/p/12128458.html
时间: 2024-10-09 00:10:36