快速排序解析

快速排序法原理也是用了分治法,主要原理是將數組分爲A[p..q-1] 和A[q+1..r],然後調整元素使得A[p..q-1]小於等於q,也小於等於A[q+1..r]。然後不斷的遞歸,到最後就排序完成。

上代碼:

  1. // QuickSort.cpp : 定義控制檯應用程序的入口點。  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include<iostream>  
  6. using namespace std;  
  7.   
  8. /*函數聲明*/  
  9. void QuickSort(int *A,int p,int r); //快速排序  
  10. int Partition(int *A,int p,int r);      //分治法  
  11. void Display(int *a,int size);          //打印函數  
  12.   
  13. /*主函數*/  
  14. int _tmain(int argc, _TCHAR* argv[])  
  15. {  
  16.     int size,*a;  
  17.     while(1)  
  18.     {  
  19.         cout<<"輸入字符串長度:"<<endl;  
  20.         cin>>size;  
  21.         if(size > 0) {  
  22.             cout<<"請輸入"<<size<<"個待排序數字:"<<endl;  
  23.             a = (int*)malloc(size*sizeof(int)); //a = new int [size];  
  24.             for(int i=0; i<size; i++)  //輸入數組  
  25.             {  
  26.                 cin>>a[i];  
  27.             }  
  28.             QuickSort(a,0,size-1); //調用快速排序函數  
  29.         }  
  30.         else  
  31.             cout<<"輸入長度錯誤!"<<endl;  
  32.   
  33.         Display(a,size);   //打印數組  
  34.     }  
  35.     return 0;  
  36. }  
  37.   
  38. /*函數定義*/  
  39. void QuickSort(int *A,int p,int r) //快速排序  
  40. {  
  41.     int q;  
  42.     if(p<r)               //如果p大於等於r 那麼就程序不執行  
  43.     {  
  44.         q = Partition(A,p,r);  //調用分治法 找到q的值  
  45.         QuickSort(A,p,q-1);  
  46.         QuickSort(A,q+1,r);  
  47.     }  
  48. }  
  49.   
  50. int Partition(int *A,int p,int r) //分治法,作用就是將數組分爲A[p..q-1] 和A[q+1..r]  
  51. {                                                   //然後調整元素使得A[p..q-1]小於等於q,也小於等於A[q+1..r]  
  52.     int x,i,j,temp;  
  53.   
  54.     x = A[r];  //將最後一個值保存在x中  
  55.     i = p-1;   //開始的時候將i 移動到數組的外面  
  56.     for( j=p; j<=r-1; j++)  
  57.     {  
  58.         if(A[j]<=x)  
  59.         {  
  60.             i +=1;  
  61.             temp = A[i]; //exchange  
  62.             A[i] = A[j];  
  63.             A[j] = temp;  
  64.         }  
  65.     }  
  66.   
  67.     temp = A[i+1];  //exchange  
  68.     A[i+1] = A[r];  
  69.     A[r] = temp;  
  70.   
  71.     return i+1;  //返回q值  
  72. }  
  73.   
  74. void Display(int *a,int size)  //打印函數  
  75. {  
  76.         cout<<"排序結果爲:"<<endl;  
  77.         for(int i=0; i<size; i++)    //打印數組  
  78.         {  
  79.             cout<<a[i]<<" ";  
  80.         }  
  81.         cout<<endl<<endl;  
  82. }  


下面我們測試一組數組: 2 8 7 1 3 5 6 4

其中第一次分治法調用示意圖如下: 


轉載自:http://blog.csdn.net/wolinxuebin/article/details/7456330

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