快速排序
快速排序的关键在于选取序列或者是文件的哪一个元素作为边界,理想情况下必须选择序列的中间元素。快速排序不适合对小型的序列进行排序。数目小的时候插入排序的效率高于快速排序。
快速排序是在所有同数量级(nlogn)的排序方法中,性能最好的。但是如uochushi记录序列按关键字有序或者基本有序时,快速排序将蜕化为冒泡排序,其时间复杂度为O(n2).而且在快速排序中需要一个栈的结构来存放每次递归的数据,在最坏的情况下,栈的最大深度为n.
若是改进快速排序,在一趟排序后比较分割所得两部分的长度。且先对长度段的子序列中的记录进行快速排序,则栈的最大深度可降为O(logn)
思想:
建立一个分区,将比其大的元素置于前面,比其小的元素置于后面,得到一个位置,然后进行递归,继续进行分区分别的排序。
void FastSort(int *fastSortArray,int start,int end)
{
if(start<end)
{
int potion=Parition(fastSortArray,start,end);
cout<<"start: "<<start<<" end: "<<end<<endl;
for(int index=0;index<10;index++)
{
cout<<*(fastSortArray+index)<<" ";
}
cout<<endl<<endl;
if(potion-start<=end-potion)
{
FastSort(fastSortArray,start,potion-1);
FastSort(fastSortArray,potion+1,end);
}
else
{
FastSort(fastSortArray,start,potion-1);
}
}
}
int Parition(int *fastSortArray,int start,int end)
{//关键在于临界值的处理
int location=start;
int compareData=*(fastSortArray+location);
cout<<"比较数据是: "<<compareData<<endl;
while(start<end)
{
while(*(fastSortArray+start+1)<compareData&&start<end)//从比较数据的后面一个开始进行比较
start++;
while(*(fastSortArray+end)>compareData&&start<end)
end--;
if (start<end)
{
int temp=*(fastSortArray+start+1);
*(fastSortArray+start+1)=*(fastSortArray+end);
*(fastSortArray+end)=temp;
}
}
if (start<=end)//当确定比较元素应该加入的位置时,交换值。
{
*(fastSortArray+location)=*(fastSortArray+start);
*(fastSortArray+start)=compareData;
}
return (start);
}
小结:1、在进行快速排序或者是这种分治排序中最主要的是处理好临界值,index的问题。