经典排序之快排--数组模拟快排

 1 #include <stdio.h>
2
3 int partition(int *a,int low ,int high)
4 {
5 int privotpos;
6 int tem = a[low];
7 privotpos = a[low];
8 while(low<high)
9 {
10 while(low<high && a[high]>=privotpos)high--;
11 a[low] = a[high];
12 while(low<high && a[low]<=privotpos)low++;
13 a[high] = a[low];
14 }
15 a[low] = tem;
16 return low;
17 }
18
19 void sort(int *a,int low,int high)
20 {
21 int privotpos;
22 if(low<high)
23 {
24 privotpos = partition(a,low,high);
25 sort(a,low,privotpos-1);
26 sort(a,privotpos+1,high);
27 }
28 }
29
30 int main()
31 {
32 int i,*p;
33 int length;
34 int a[12];
35 // length = a.length();
36 length = 10;
37 printf("Enter 10 numbers:\n");
38 for(i = 0; i < length; i++)
39 // scanf("%d",(a+i));
40 scanf("%d",&a[i]);
41
42 printf("Before ordered:\n");
43 for(i = 0; i < length; i++)
44 printf("%d ",*(a+i));
45 printf("\n\n");
46 // quick sort
47 // p = a;
48 sort(a,0,length-1);
49
50 printf("After ordered:\n");
51 for(i = 0; i < length; i++)
52 printf("%d ",*(a+i));
53 printf("\n");
54 return 0;
55 }

快排原理,每次找一个标志位,然后遍历数组,大于该位的放在其前边,小于该位的放于其后边,然后在对两侧的小数组进行便如此计算,知道排好序为止。代码如上。

posted on 2012-03-25 12:33  NewPanderKing  阅读(724)  评论(0编辑  收藏  举报

导航