您的位置:首页 > 编程语言 > C语言/C++

Quick Sort (快速排序 C++)

2013-02-18 17:03 197 查看
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.waitingfy.com/?p=415
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: