快速排序

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93

#include <stdio.h>
#include <stdlib.h>

#define MAXN 100
int num[MAXN] = {4,9,7,3,2,0,1,8,6,5};

void print(int *a, int n)
{
for(int i = 0; i < n; ++i)
printf("%d ",a[i]);
puts("");
}

void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}

//定轴法
void quickSortOne(int *a, int l, int r)
{
if(l > r) return ;
int i = l, j = r;
int axi = a[l];
while(i != j)
{
while(i < j && a[j] >= axi)
--j;
while(i < j && a[i] <= axi)
++i;
if(i < j)
swap(&a[i], &a[j]);
}
a[l] = a[i];
a[i] = axi;
quickSortOne(a, l, i-1);
quickSortOne(a, i+1, r);
}

//挖坑法
void quickSortTwo(int *a, int l, int r)
{
if(l > r) return ;
int i = l, j = r;
int axi = a[l];
while(i != j)
{
while(i < j && a[j] >= axi)
--j;
a[i] = a[j];
while(i < j && a[i] < axi)
++i;
a[j] = a[i];
}
a[i] = axi;
quickSortTwo(a, l, i-1);
quickSortTwo(a, i+1, r);
}

//采用了挖坑法实现一个统一的排序
void mySort(int *a, int l, int r, int (*comp)(void*, void*))
{
if(l > r) return;
int i = l, j = r;
int axi = a[l];
while(i != j)
{
while(i < j && !comp(&a[j], &axi))
--j;
a[i] = a[j];
while(i < j && comp(&a[i], &axi))
++i;
a[j] = a[i];
}
a[i] = axi;
mySort(a, l, i-1, comp);
mySort(a, i+1, r, comp);
}

int cmp(int *a , int *b)
{
return *a < *b;
}

int main()
{
mySort(num, 0, 9, cmp);
print(num,10);
return 0;
}