《算法》第二章——快排非递归实现

思路:

其实就是用栈保存每一个待排序子串的首尾元素下标,下一次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;
}


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