快排的递归和非递归实现

[cpp]  view plain  copy
  1. //快排的递归  
  2. void quickSort1(int* root,int low,int high)  
  3. {  
  4.     int pat=root[low];  
  5.     if(low<high)  
  6.     {  
  7.         int i=low,j=high;  
  8.         while(i<j)  
  9.         {     
  10.             while(i<j&&root[j]>pat)  
  11.                 j--;  
  12.             root[i]=root[j];  
  13.   
  14.   
  15.             while(i<j&&root[i]<pat)  
  16.                 i++;  
  17.             root[j]=root[i];  
  18.   
  19.         }  
  20.         root[i]=pat;  
  21.         quickSort1(root,low,i-1);  
  22.         quickSort1(root,i+1,high);  
  23.     }  
  24.       
  25. }  
  26.   
  27. //快排的非递归  
  28. int partion(int* root,int low,int high)  
  29. {  
  30.     int part=root[low];  
  31.     while(low<high)  
  32.     {  
  33.         while(low<high&&root[high]>part) high--;  
  34.         root[low]=root[high];  
  35.         while(low<high&&root[low]<part) low++;  
  36.         root[high]=root[low];  
  37.     }  
  38.     root[low]=part;  
  39.     return low;  
  40. }  
  41.   
  42. void quickSort2(int* root,int low,int high)  
  43. {  
  44.     stack<int> st;  
  45.     int k;  
  46.     if(low<high)  
  47.     {  
  48.         st.push(low);  
  49.         st.push(high);  
  50.         while(!st.empty())  
  51.         {  
  52.             int j=st.top();st.pop();  
  53.             int i=st.top();st.pop();  
  54.   
  55.             k=partion(root,i,j);  
  56.   
  57.             if(i<k-1)  
  58.             {  
  59.                 st.push(i);  
  60.                 st.push(k-1);  
  61.             }  
  62.             if(k+1<j)  
  63.             {  
  64.                 st.push(k+1);  
  65.                 st.push(j);  
  66.             }  
  67.         }  
  68.   
  69.     }  
  70.       
  71. }  
  72.   
  73. int main()  
  74. {  
  75.     int a[8]={4,2,6,7,9,5,1,3};  
  76.     quickSort1(a,0,7);  
  77.     //quickSort2(a,0,7);  
  78.     int i;  
  79.     for(i=0;i<8;i++)  
  80.         cout<<a[i]<<"   ";  
  81.     cout<<endl;  
  82.     getchar();  
  83.     return 0;  
  84. }  


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值