天天看点

Sort : QuickSort

自己写的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;
}