快速排序演算法遞迴與非遞迴實現(二)

來源:互聯網
上載者:User

快速排序是對冒泡排序的一種改進。它的基本思想是:通過一躺排序將要排序的資料分割成獨立的兩部分,其中一部分的所有資料都比另外一不部分的所有資料都要小,然後再按次方法對這兩部分資料分別進行快速排序,整個排序過程可以遞迴或者非遞迴進行,以此達到整個資料變成有序序列。

快速排序的遞迴演算法:

   void qsort(int a[],int left,int right)

  {

       int pivot,l,r,temp;

      

       l = left;

       r = right;

       pivot = a[(left+right)/2]; //取中位值作為分界值

 

       while(l<r)

       {

          while(a[l] < pivot) ++l;

          while(a[r] > pivot) --r;

      

          if(l>=r) break;

 

          temp = a[l];

          a[l] = a[r];

          a[r] = temp;

          ++l;

           --r;

        }

       

         if(l==r) l++;

         if(left < r) qsort(a, left,l-1);

         if(l < right) qsort(a,r+1,right);

  }

 

快速排序的非遞迴演算法#include <iostream>
#include <stack>
using namespace std;
template <class T>
int partition(T a[],int low,int high)
{
 T v=a[low];
 while(low<high)
 {  
  while(low<high && a[high]>=v) high--;
  a[low]=a[high];
  while(low<high && a[low]<=v) low++;
  a[high]=a[low];
 }
 a[low]=v;
 return low;
 
} template <class T>
void QuickSort(T a[],int p,int q)
{
 stack<int> st;
 int j;
 do{
      while(p<q)
      {
         j=partition(a,p,q);   
         if( (j-p)<(q-j) )
         {
            st.push(j+1);
            st.push(q);
            q=j-1;
         }
         else
         {
           st.push(p);
           st.push(j-1);
           p=j+1;
         }   
      }
  if(st.empty()) return;
  q=st.top();st.pop();  
  p=st.top();st.pop();  
  //cout<<endl<<"p:"<<p<<" ";
  //cout<<"q:"<<q<<endl;
 }while(1);
}void main()
{
 //int a[7]={7,6,5,4,3,2,1};
 //int a[7]={1,2,3,4,5,6,7};
 int a[7]={3,5,2,3,66,225,1};
 for(int i=0;i<7;i++)
  cout<<a[i]<<" ";
 QuickSort(a,0,6);
 cout<<endl;
 for(int i=0;i<7;i++)
  cout<<a[i]<<" ";
}  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.