《算法》第二章——快排非遞歸實現

思路:

其實就是用棧保存每一個待排序子串的首尾元素下標,下一次while循環時取出這個範圍,對這段子序列進行partition操作。

代碼:

#include<iostream>
#include<stack>

using namespace std;

int partition(int *a,int lo,int hi)
{//每次取第一個元素爲pivot
  int pivot = a[lo];

  while(lo < hi)
  {
    //lo位置的數被存起來了,所以先從hi往前找第一個較小的元素,然後放到lo處
    while(lo < hi && pivot <= a[hi])
      hi--;
    a[lo] = a[hi];

    //hi位置的數被存起來了,所以從lo往前找第一個較大的元素,然後放到hi處
    while(lo < hi && pivot >= a[lo])
      lo++;
    a[hi] = a[lo];
  }
  /*此時lo == hi*/
  a[lo] = pivot;

  return lo;
}

//非遞歸算法
void quicksort(int *a,int lo,int hi)
{
  stack<int> st;

  if(lo < hi)
  {
//    int p = partition(a,lo,hi);
//    if(lo < p - 1)
//    {
//      st.push(lo);
//      st.push(p-1);
//    }
//    if(p + 1< hi)
//    {
//      st.push(p+1);
//      st.push(hi);
//    }
    st.push(lo);
    st.push(hi);
  }

  while(!st.empty())
  {
    int hi_t = st.top();
    st.pop();//注意棧是後進先出的
    int lo_t = st.top();
    st.pop();

    int p = partition(a,lo_t,hi_t);
    if(lo_t < p - 1)
    {
      st.push(lo_t);
      st.push(p-1);
    }
    if(p + 1< hi_t)
    {
      st.push(p+1);
      st.push(hi_t);
    }
  }
}

int main()
{
  int a[]={3,4,2,1,6,3,4};
  int len = sizeof(a)/sizeof(int);
  quicksort(a,0,len - 1);
  for(int i = 0;i < len;i++)
    cout<<a[i]<<" ";
  cout<<endl;
}


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