快速排序法原理也是用了分治法,主要原理是將數組分爲A[p..q-1] 和A[q+1..r],然後調整元素使得A[p..q-1]小於等於q,也小於等於A[q+1..r]。然後不斷的遞歸,到最後就排序完成。
上代碼:
- // QuickSort.cpp : 定義控制檯應用程序的入口點。
- //
- #include "stdafx.h"
- #include<iostream>
- using namespace std;
- /*函數聲明*/
- void QuickSort(int *A,int p,int r); //快速排序
- int Partition(int *A,int p,int r); //分治法
- void Display(int *a,int size); //打印函數
- /*主函數*/
- int _tmain(int argc, _TCHAR* argv[])
- {
- int size,*a;
- while(1)
- {
- cout<<"輸入字符串長度:"<<endl;
- cin>>size;
- if(size > 0) {
- cout<<"請輸入"<<size<<"個待排序數字:"<<endl;
- a = (int*)malloc(size*sizeof(int)); //a = new int [size];
- for(int i=0; i<size; i++) //輸入數組
- {
- cin>>a[i];
- }
- QuickSort(a,0,size-1); //調用快速排序函數
- }
- else
- cout<<"輸入長度錯誤!"<<endl;
- Display(a,size); //打印數組
- }
- return 0;
- }
- /*函數定義*/
- void QuickSort(int *A,int p,int r) //快速排序
- {
- int q;
- if(p<r) //如果p大於等於r 那麼就程序不執行
- {
- q = Partition(A,p,r); //調用分治法 找到q的值
- QuickSort(A,p,q-1);
- QuickSort(A,q+1,r);
- }
- }
- int Partition(int *A,int p,int r) //分治法,作用就是將數組分爲A[p..q-1] 和A[q+1..r]
- { //然後調整元素使得A[p..q-1]小於等於q,也小於等於A[q+1..r]
- int x,i,j,temp;
- x = A[r]; //將最後一個值保存在x中
- i = p-1; //開始的時候將i 移動到數組的外面
- for( j=p; j<=r-1; j++)
- {
- if(A[j]<=x)
- {
- i +=1;
- temp = A[i]; //exchange
- A[i] = A[j];
- A[j] = temp;
- }
- }
- temp = A[i+1]; //exchange
- A[i+1] = A[r];
- A[r] = temp;
- return i+1; //返回q值
- }
- void Display(int *a,int size) //打印函數
- {
- cout<<"排序結果爲:"<<endl;
- for(int i=0; i<size; i++) //打印數組
- {
- cout<<a[i]<<" ";
- }
- cout<<endl<<endl;
- }
下面我們測試一組數組: 2 8 7 1 3 5 6 4
其中第一次分治法調用示意圖如下:
轉載自:http://blog.csdn.net/wolinxuebin/article/details/7456330