快排非递归算法


#include
using namespace std;

#include
#include
#include
 #include

typedef struct
{
 int low;
 int high;
}boundary;

template < typename T >
int partition( vector& vec, int low, int high)
{
 T pivot = vec[low];
 while(low < high)
 { 
  while(low < high && vec[high] >= pivot)
   high=high-1;
  vec[low] = vec[high];
  while(low < high && vec[low] <= pivot)
   low=low+1;
  vec[high] = vec[low];
 }

 vec[low] = pivot;
 return low;

}
template < typename T >
void Quick_Sort(vector& vec, int low, int high)
{
 int mid;
 stack st;
 boundary bo;
 if(low < high)
 {
  mid= partition(vec,low,high);
  if(low < mid-1)
  {
   bo.low=low;
   bo.high=mid+1;
   st.push( bo );
  }
  if(mid+1 < high)
  {
   bo.low=mid+1;
   bo.high=high;
   st.push( bo );
  }
  while(!st.empty())
  {
   boundary b1;
   int p,q;
   b1 = st.top();
   st.pop();
   q = b1.high;
   p = b1.low;
   mid = partition(vec, p, q);
   if(p < mid-1)
   {
    b1.high=mid-1;
    b1.low=p;
    st.push(b1);
   }
   if(mid+1 < q)
   {
    b1.high=q;
    b1.low=mid+1;
    st.push(b1);
   }
  
  }
 }

}

int main()
{
 int len=1000;
 vector vec;
 for(int i=0;i< len;i++)
  vec.push_back( rand() );

 clock_t t1 = clock();
 Quick_Sort( vec, 0, len-1 );
    clock_t t2 = clock();

 cout<<"recurcive"<<1.0*(t2-t1)/CLOCKS_PER_SEC<  
 random_shuffle(vec.begin(), vec.end() );

 

 for (int i = 0; i < len; i++)
 {
  cout<  }

 


 system("pause"); 
 return 0;
}

你可能感兴趣的:(数据结构,算法,pivot,include,struct,system)