經典演算法之快速排序

wardseptember發表於2017-12-08
/************************
author's email:wardseptember@gmail.com
date:2017.12.8
快速排序
************************/

/*
每一趟選擇當前所有子序列中的一個關鍵字(通常是第一個)作為樞軸,將子序列中比樞軸小的移到樞軸
前邊,比樞軸大的移到樞軸後邊;當本躺所有子序列都被樞軸以上述規則劃分完畢後會得到新的一組更短
的子序列,它們成為下一趟劃分的初始序列集。
*/
#include<iostream>
#define maxSize 10
using namespace std;
void quickSort(int *a, int low, int high);//快速排序
void printArray(int D[], int n);//輸出陣列
void main() {
	int D[maxSize] = { 12,15,48,46,16,78,57,88,65,48 };//構造一個一維陣列

	quickSort(D,0,maxSize-1);
	cout << "快速排序結果為:" << endl;
	printArray(D, maxSize);

}
void quickSort(int *a, int low,int high) {//對從a[low]到a[high]的關鍵字進行排序
	int temp, i = low, j = high;
	if (low < high) {
		temp = a[low];

		/*下面的這個迴圈完成了一趟排序,即將陣列中小於temp的關鍵字放在左邊,
		大於temp的關鍵字放在右邊*/
		while (i != j) {

			//從右到左掃描,找到一個小於temp的關鍵字
			while (j > i&&a[j] >= temp)
				--j;
			if (i < j) {
				a[i] = a[j];   //放到temp的左邊
				++i;           //i右移一位
			}

			//從左到右掃描,找到一個大於temp的關鍵字
			while (j > i&&a[i] <temp)
				++i;
			if (i < j) {
				a[j] = a[i];     //放在temp的右邊
				--j;             //j左移一位
			}
			a[j] = temp;      //此時i=j。此句可換成a[i]=temp;   將temp放在最終位置
			quickSort(a, low, j - 1);//遞迴地對temp左邊的關鍵字排序,j換成i一樣
			quickSort(a, j + 1, high);//遞迴地對temp右邊的關鍵字排序,j換成i一樣
		}
	}
}
void printArray(int D[], int n) {
	for (int i = 0; i < n; ++i)  //輸出排序後的關鍵字
		cout << D[i] << " ";
	cout << endl;
}
以上如有錯誤,請指出,大家共同學習進步

相關文章