自己寫的QuickSort,主函數部分可以忽略不計。
QuickSort的中心思想:把“大數組大數組”劃歸成“兩個小數組排序”。關鍵步驟是Partition(劃分)部分,把序列分成兩個子序列,不超過PIvot的部分和大于Pivot的部分。
QuickSort中的形參表,第一個元素l,和最後一個元素h在數組S中的下标。
#include <iostream>
using namespace std;
void swap(int* a, int* b)
{
int temp;
temp = *b;
*b = *a;
*a =temp;
}
int partition(int s[], int l, int h)
{
int i;
int p;
int firsthigh;
p = h;
firsthigh = l;
for (i = l; i<h; i++)
{
if (s[i]<s[p])
{
swap(&s[i],&s[firsthigh]);
firsthigh++;
}
}
swap(&s[p],&s[firsthigh]);
return firsthigh;
}
void quicksort(int s[], int l, int h)
{
int p;if ((h-l)>0)
{
p = partition(s, l, h);
quicksort(s, l, p-1);
quicksort(s, p+1, h);
}
}
int main()
{
int a[10]={1,6,8,10,3,2,7,8,0,17};
quicksort(a,0,9);
for (int i=0; i<10; i++)
{
cout<<a[i]<<endl;
}
return 0;
}