排序

几个排序方式的模板

冒泡排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

using namespace std;

int a[100],n;

int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
scanf("%d", &a[i]);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n - i; j++)
if (a[j] > a[j + 1])
swap(a[j], a[j + 1]);
for (int i = 1; i <= n; i++)
printf("%d ", a[i]);
return 0;
}

快速排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <cstdio>

using namespace std;

const int MAXN = 1e6 + 10;

int a[MAXN];
int n;

void quicksort(int l, int r)
{
if (l == r)
return;
int x = a[(l + r + 1) / 2], i = l - 1, j = r + 1; //int x=a[(l+r)/2]
while (i < j)
{
while (a[++i] < x);
while (a[--j] > x);
if (i < j)
swap(a[i], a[j]);
}
quicksort(l, i - 1); //quicksort(l,j);
quicksort(i, r); //quicksort(j+1,r);
}

int main()
{
scanf("%d", &n);
for (int i = 1; i <= n; i++)
scanf("%d", &a[i]);
quicksort(1, n);
for (int i = 1; i <= n; i++)
printf("%d ", a[i]);
return 0;
}

归并排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>

using namespace std;

const int N = 1e6 + 10;

int a[N], tem[N], n;

void mergesort(int a[], int l, int r)
{
if (l >= r)
return;
int mid = (l + r) / 2;
mergesort(a, l, mid), mergesort(a, mid + 1, r);
int k = 0, i = l, j = mid + 1;
while (i <= mid && j <= r)
{
if (a[i] < a[j])
tem[k++] = a[i++];
else
tem[k++] = a[j++];
}
while (i <= mid)
tem[k++] = a[i++];
while (j <= r)
tem[k++] = a[j++];
for (int i = 0; i < k; i++)
a[l + i] = tem[i];
}

int main()
{
scanf("%d", &n);
for (int i = 1; i <= n; i++)
scanf("%d", &a[i]);
mergesort(a, 1, n);
for (int i = 1; i <= n; i++)
printf("%d ", a[i]);
return 0;
}