快速排序解析

来源:互联网 发布:淘宝如何举报盗图 编辑:程序博客网 时间:2024/04/29 10:00

快速排序法原理也是用了分治法,主要原理是将数组分为A[p..q-1] 和A[q+1..r],然后调整元素使得A[p..q-1]小于等于q,也小于等于A[q+1..r]。然后不断的递归,到最后就排序完成。

上代码:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  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

0 0