快速排序算法

步驟來自維基百科

步驟爲:

  1. 從數列中挑出一個元素,稱爲 "基準"(pivot),
  2. 重新排序數列,所有元素比基準值小的擺放在基準前面,所有元素比基準值大的擺在基準的後面(相同的數可以到任一邊)。在這個分割結束之後,該基準就處於數列的中間位置。這個稱爲分割(partition)操作。
  3. 遞歸地(recursive)把小於基準值元素的子數列和大於基準值元素的子數列排序。

遞迴的最底部情形,是數列的大小是零或一,也就是永遠都已經被排序好了。雖然一直遞迴下去,但是這個算法總會結束,因爲在每次的迭代(iteration)中,它至少會把一個元素擺到它最後的位置去。


#include <iostream>
#include <string>
#include <algorithm>


using namespace std;


/*void swap(int *a,int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}*/


void Quick_Sort(int a[],int left,int right)
{
int tmp = a[left];
int low = left;
int height = right;
if(left>=right)
return;
while(low<height)
{
while(height>low&&a[height]>=tmp)
height--;
swap(a[low],a[height]);
while(low<height&&a[low]<tmp)
low++;
swap(a[height],a[low]);
}
Quick_Sort(a,left,height-1);
Quick_Sort(a,height+1,right);
}


int main()
{
int num[] = {2,5,7,1,8,4,6,8,1,0};
int i;
Quick_Sort(num,0,sizeof(num)/sizeof(num[0])-1);
for(i = 0;i<sizeof(num)/sizeof(num[0]);i++)
cout<<num[i]<<" ";
cout<<endl;
return 0; 
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章