introduction to algorithms sorting lesson_4 quick sorting

来源:互联网 发布:顺序表的逆置c语言 编辑:程序博客网 时间:2024/05/17 07:16

快速排序是众多排序中平均性能最好最快的排序算法

其基本思想是:通过一次排序,将数据记录分割成两部分,一部分小于某个关键值,即枢轴,另一部分大于枢轴。

然后在分别对两部分又进行快速排序,即用递归方式进行,一般枢轴取第一个数据

先来看分割数据部分代码,返回枢轴位置

/**********quick sorting  algorithm**************/int  parting(int data[],int left,int right){int low=left;int high=right;int pivotkey=data[low];while (low<high){while(low<high&&data[high]>=pivotkey)high--;//找到右边第一个小的数据然后交换data[low]=data[high];while(low<high&&data[low]<=pivotkey)low++;//找到左边第一个大的数据然后交换data[high]=data[low];}data[low]=pivotkey;//记录枢轴数据return low; //返回枢轴位置}
然后就可以运用递归的方法实现排序:

void quikcsort(int data[],int left,int right){if (left<right){int pivotloc=parting(data,left,right);//一分为二quikcsort(data,left,pivotloc-1);//排左边quikcsort(data,pivotloc+1,right);//排右边}}

测试:

#define getArraySize(arrayName) (sizeof(arrayName)/sizeof(arrayName[0]))

int _tmain(int argc, _TCHAR* argv[]){int data_test[10]={1,0,2,9,3,1,5,8,9,10};quikcsort(data_test,0,getArraySize(data_test)-1);//getArraySize 获取数组长度函数prtarray(data_test,getArraySize(data_test));//打印数组system("pause");return 0;}
分析:

      快速排序的时间复杂度为O(knlogn),其中k值在众多排序方法中,快速排序平均性能最好,即k最小

      可以对比归并排序算法,其思路与快速排序类似 参考lesson 2 merge sorting


0 0