【排序】快速排序

来源:互联网 发布:腾讯内部员工网络 编辑:程序博客网 时间:2024/05/17 09:27

冒泡的问题

当排序的数据比较多时排序的时间会明显延长,因此我们需要更快的排序策略,快速排序应运而生!

基本思想是

通过一趟排序将要排序数据成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以

递归进行,以此达到整个数据变成有序序列。

缺点

多个相同的值的相对位置也许会在算法结束时产生变动。

/*文件名:user.c摘要:排序应用文件完成日期:2012-7-11作者:学生版本:1.0*/#include <stdio.h>#include "qs.h"#define N 10int main(){     int a[] = {0, 11, 12, 5, 6, 13, 14,  8, 9, 7, 10};     printf("Initial arry:\n");     PrintArry(a, N); //输出数组     QuickSort(a, N);//排序     printf("After quicksorting:\n");     PrintArry(a, N);     return 0;}



 

/*文件名:qs.h摘要:函数的声明完成日期:2012-7-11作者:学生版本:1.0*/#ifndef QS_H_INCLUDED#define QS_H_INCLUDEDint Partitions(int a[], int low, int high);void Qsort(int a[], int low, int high);void QuickSort(int a[], int n);void PrintArry(int a[], int n);#endif // QS_H_INCLUDED


 

/*文件名:qs.c摘要:函数的定义完成日期:2012-7-11作者:学生版本:1.0*/#include <stdio.h>#include "qs.h"/*功能:排序辅助函数输入:int a[], int low, int high输出:low*/int Partitions(int a[], int low, int high) //a 0 n{     int pivotkey = a[low]; //第一次调用时,pivotkey = a[0]     while (low < high)     {          while (low < high && a[high] >= pivotkey)//从末尾开始查找,直到找到比pivotkey小的数为止          {               --high;          }          a[low] = a[high];//找到了第一个比pivotkey小的数          while(low < high && a[low] <= pivotkey)//从首部开始,直到找到比pivotkey大的数为止          {               ++low;          }          a[high] = a[low];//找到了第一个比pivotkey大的数     }     a[low] = pivotkey;     return low;}/*功能:排序函数思路:递归输入:int a[], int low, int high函数调用:自己*/void Qsort(int a[], int low, int high){     int pivottag = 0;     if (low < high)     {          pivottag = Partitions(a, low, high); //a 0 n          Qsort(a, low, pivottag - 1); //先对左边排序          Qsort(a, pivottag + 1, high);//后对右边排序     }}/*功能:快排调用函数输入:int a[], int n函数调用:void Qsort(int a[], int low, int high)*/void QuickSort(int a[], int n){     Qsort(a, 0, n);}/*功能:输出数组输入:int a[], int n函数调用:void printf(const char *__format, ...)*/void PrintArry(int a[], int n){     int i = 0;     for (i = 0; i < n; i++)     {          printf("%3d", a[i]);     }     printf("\n");}


 

原创粉丝点击