夜深人靜寫算法——快速排序(分治)

快速排序:採用分治的方法

 (一):

     (1) 將數組的第一個作爲參考值,將所有小於該值的數移動到改值左側,將所有大於該值的數移動到數組右側(利用兩個指針分別從數組的首尾開始向中間掃描);

    (2)將參考值的左側和右側看作新的兩個數組

    (3)重新從(1)開始,直到數組的大小爲0;

 

(二);

   如圖爲第一次遞歸,將小於23的移到左側,大於23的移到右側。

 

 

(三):

 程序如下:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
using namespace std;

template <class Type>
void swap(Type *a,Type *b){
	Type c;
	c = *a;
	*a = *b;
	*b = c;
}

template <class Type>
void QuickSort(Type a[],int l,int r){ //排序從l到r的數組
	if(l < r){  // 如果l >= r 不進行操作
		int t = l;     
		int stl = l;  //stl爲左側的指針
		int str = r+1; //str爲右側指針
		while(true){
			while(a[++stl] <= a[t] && stl <= r); //stl掃描到大於 參考值 的值後停止掃描
			while(a[--str]> a[t] && str >= 0);  //str掃描到小於 參考值 的值後停止掃描
			if(str < stl)break;  //如果當前str小於stl 說明掃描完一遍,最外層while循環停止
			swap(&a[stl],&a[str]);  //交換兩個指針的值
		}
		swap(&a[l],&a[str]);  //交換參考值和str指針指向的值
		QuickSort(a,l,str-1); //參考值左側數組遞歸
		QuickSort(a,str+1,r);  //參考值右側數組遞歸
	}
	
}
int main(){
	int a[10] = {4,3,2,6,1,5,7,9,8,0};
	
	
	for(int i = 0;i < 10 ;i++){
		cout<<a[i];
		if(i == 9)cout<<endl;
		else cout<<" ";
	}
	QuickSort(a,0,9);
	
	cout<<"排序後"<<endl; 
	for(int i = 0 ;i < 10;i++){
		cout<<a[i];
		if(i == 9)cout<<endl;
		else cout<<" ";
	}
	return 0;
} 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章