快速排序例程

#include <iostream>
using namespace std;

void Swap(int& p1, int& p2)
{
	int temp = p1;
	p1 = p2;
	p2 = temp;
}

void Qsort(int* array, int start, int end)
{
	if(start < end)
	{
		int pivot = array[start];
		int pLeft = start + 1;
		int pRight = end;
	
		while(pLeft <= pRight)
		{
			while(pLeft <= pRight && array[pRight] >= pivot)
				--pRight;
			while(pLeft <= pRight && array[pLeft] < pivot)
				++pLeft;
			if(pLeft < pRight)
				Swap(array[pRight], array[pLeft]);
		}
		Swap(array[start], array[pRight]);

		Qsort(array, start, pRight - 1);
		Qsort(array, pRight + 1, end);
	}
}

void QuickSort(int* array, int length)
{
	if(array == NULL || length <= 0)
		return;
	Qsort(array, 0, length - 1);
}

int main()
{
	int a[] = {3,2,5,3,4,6,1,6,7,5,9};
	QuickSort(a, 11);
	for(int i = 0; i < 11; ++i)
		cout << a[i] << " ";
	cout << endl;
	getchar();
}

你可能感兴趣的:(快速排序例程)