目录:
快速排序
归并排序
二分
快速排序 —— 分治:
1.确定边界,一般有三种方法:
① 取左边界,x =
②取右边界,x =
③取中间点,x =
2.调整区间:![\color{red}{\bigstar}](https://latex.csdn.net/eq?%5Ccolor%7Bred%7D%7B%5Cbigstar%7D)
①
x的放到a里边
②
x的放到b里面
3.递归处理左右两端
代码:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;
int a[maxn] , n;
inline void Sort (int a[] , int l , int r) {
if (l >= r)return;
int i = l - 1 , j = r + 1 , x = a[(l + r) >> 1];
while (i < j) {
do i ++; while (a[i] < x);
do j --; while (a[j] > x);
if (i < j)swap (a[j] , a[i]);
}
Sort (a , l , j);
Sort (a , j + 1 , r);
}
int main() {
scanf ("%d" , &n);
for (int i = 1; i <= n; ++ i)scanf ("%d" , &a[i]);
Sort (a , 1 , n);
for (int i = 1; i <= n; ++ i)printf ("%d " , a[i]);
return 0;
}
时间复杂度: 。
-----------------------------------华丽的分割线-----------------------------------------
归并排序 —— 分治 ![O(nlongn)](https://latex.csdn.net/eq?O%28nlongn%29)
左边 右边
|-----------------|-----------------------|
①确定分界点:![mid = (l+r)>>1](https://latex.csdn.net/eq?mid%20%3D%20%28l+r%29%3E%3E1)
②递归处理
③归并——合二为一
![O(n)](https://latex.csdn.net/eq?O%28n%29)
双指针:
如果i指针比j指针上的数小即
,那么把
放到res里,
,否则把
放res
里,
,如果i到头了或者j到头了,那么把剩下的数都放到res里。
代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
inline int read() {//快读
int f = 0 , w = 1;
char c = getchar();
while (c < '0' || c > '9') {
if (c == '-')w = -1;
c = getchar();
}
while (c >= '0' && c <= '9')
f = (f << 1) + (f << 3) + (c ^ 48) , c = getchar();
return f * w;
}
inline void print(int num) {//快输
if (num < 0)num = -num , putchar('-');
if (num > 9)print(num / 10);
putchar(num % 10 + '0');
}
int n;
int q[N] , tmp[N];
inline void merge_sort (int q[] , int l , int r) {
if (l >= r)return;
int mid = l + r >> 1;
merge_sort (q , l , mid);
merge_sort (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 (int i = l , j = 0; i <= r; ++ i , ++ j) q[i] = tmp[j];
}
int main() {
n = read ();
for (int i = 1; i <= n; ++ i)q[i] = read ();
merge_sort (q , 1 , n);
for (int i = 1; i <= n; ++ i) print(q[i]) , putchar (' ');
return 0;
}