快速排序

May 13, 2015


#include <iostream>

using namespace std;

void swap(int arr[], const int& l, const int& r)
{
	int  temp = arr[l];
	arr[l] = arr[r];
	arr[r] = temp;
}

void qsort(int arr[], int left, int right)
{
	int i,last;
	if (left >= right) return;

	last = left;

	for(i = left+1; i<=right; i++)
		if( arr[i]< arr[left])
			swap(arr,++last,i);
	swap(arr,left,last);
	qsort(arr,left,last-1);
	qsort(arr,last+1,right);
}

int main(void)
{
	int arr[] = {3,5,3,7,2,9,0,4,8,1,1,3,5,6,7,8,4,2,6,7,5,3,34,2,3,6,7,54,3,7};
	int len = sizeof(arr)/sizeof(int);
	qsort(arr,0,len - 1);
	for( int i = 0; i < len; i++)
	{
		cout<<arr[i]<<" ";
	}
	cout<<endl;
	return 0;
}