码迷,mamicode.com
首页 > 编程语言 > 详细

快速排序

时间:2015-10-05 00:44:10      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

 1 /*
 2 时间:2015年9月26日21:34:10
 3 描述:对数组a[]中元素排序
 4 功能:快速排序
 5 */
 6 # include <stdio.h>
 7 
 8 int FindPos(int *, int, int);
 9 void QuickSort(int *, int, int);
10 
11 int main(void)
12 {
13     int i;
14     int a[6] = {5, 8, 7, -9, 0, 6};
15     QuickSort(a, 0, 5);//第二个参数是第一个元素的下标,第三个参数是最后一个元素的下标
16 
17     for (i=0; i<6; i++)
18         printf("%d  ", a[i]);
19     printf("\n");
20 
21     return 0;
22 }
23 
24 /*
25 函数:void QuickSort(参数1, 参数2, 参数3)
26 功能:快速排序的循环
27 参数:1.数组地址。2.某一半元素的低位。3.高位
28 返回值:无
29 */
30 void QuickSort(int * a, int low, int high)
31 {
32     int pos;
33     if (low < high)
34     {
35         pos = FindPos(a, low, high);
36         QuickSort(a, low, pos-1);
37         QuickSort(a, pos+1, high);
38     }
39 }
40 
41 /*
42 函数:int FindPos(参数1, 参数2, 参数3)
43 功能:查找a[low]的位置
44 参数:1.数组地址。2.某一半元素的低位。3.高位
45 返回值:a[low]的位置,int型
46 */
47 int FindPos(int * a, int low, int high)
48 {
49     int val = a[low];
50     while (low < high)
51     {
52         while (low < high && a[high] > val)//注意此处low < high不能丢!
53             high--;
54         a[low] = a[high];
55         while (low < high && a[low] < val)
56             low++;
57         a[high] = a[low];
58     }//循环终止时,low = high
59     a[low] = val;
60     return low;
61 }
62 
63 /*
64 在VC++6.0输出结果是:
65 ----------------------------
66 -9  0  5  6  7  8
67 Press any key to continue
68 ----------------------------
69 */

 

快速排序

标签:

原文地址:http://www.cnblogs.com/moon1992/p/4855239.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!