Quick Sort C++

Below is the core code
template <class T>
int Partition(T a[], int p, int r){
    int x = a[r];
	int i = p - 1;
	for(int j = p;j <= r - 1;j++){
		if(a[j] <= x){
			i++;
			swap(a[i],a[j]);
		}
	}
	swap(a[i + 1],a[r]);
	return i + 1;
}
Figure below show how Partition works on an 8-element array. Array entry a[r] becomes the pivot element x. Lightly shaded array elements are all in the first partition with values no greater than x. Heavily shaded elements are in the second partition with values greater than x.   We compared the array entry a[j] and element x, if it is greater than x, stay it along. So greater partition grows. However, if it is smaller than x, it and the first great element are swapped, the smaller partition grows. Continuing in this way. At last, x element and the first great element are swapped. As a result, all left elements are small than x, all right elements are greater than x.
// QuickSort.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>

using namespace std;

template <class T>
void PrintfNum(T a[], int n);

template <class T>
int Partition(T a[], int p, int r){
    int x = a[r];
	int i = p - 1;
	for(int j = p;j <= r - 1;j++){
		if(a[j] <= x){
			i++;
			swap(a[i],a[j]);
		}
	}
	swap(a[i + 1],a[r]);
	return i + 1;
}
template <class T>
void QuickSort(T a[], int p, int r){
    if(p < r){
		int q = Partition(a, p, r);
		QuickSort(a, p, q - 1);
		QuickSort(a, q + 1, r);
	}
}

int main(int argc, char* argv[])
{
	int a[8]={2,8,7,1,3,5,6,4};
	cout << "Before sort:" << endl;
	PrintfNum(a, 8);
	cout << endl;

	cout << "Partion Once:" << endl;
	Partition(a, 0 ,7);
    PrintfNum(a, 8);
	cout << endl;

	cout << "After sort:" << endl;
	QuickSort(a, 0, 7);
    PrintfNum(a, 8);
	return 0;
}

template <class T>
void PrintfNum(T a[], int n){
	for(int i = 0; i < n; i++){
		cout << a[i] << ",";
	}
	cout << endl;
}
  Result:   Reference: <INTRODUCTION TO ALGORITHMS> third edition http://www.easycpp.com/?p=9
posted @ 2013-10-18 17:18  easycpp  阅读(331)  评论(0编辑  收藏  举报