快速排序
/* 实现快速排序的非递归版本 */ #include <stdio.h> #include <stdlib.h> #include <iostream> #include <stack> #include <vector> using namespace std; #define MAX 100 typedef struct node { int nLow; int nHigh; }data; template<typename T> int Partition(vector<T> vect , int nLow , int nHigh) { int pivot = vect[nLow]; while(nLow < nHigh) { while(nLow < nHigh && vect[nHigh] >= pivot) { --nHigh; } if(nLow < nHigh) { vect[nLow++] = vect[nHigh]; } while(nLow < nHigh && vect[nLow] <= pivot) { ++nLow; } if(nLow < nHigh) { vect[nHigh--] = vect[nLow]; } } vect[nLow] = pivot; return nLow; } template<typename T> void quicksort(vector<T> vect) { stack<data *> Stack; int p = Partition(vect , 0 , length - 1); data *temp = (data*)malloc(sizeof(data)) , *newdata; temp->nLow = 0; temp->nHigh = p - 1; Stack.push(temp); // free(temp); temp = (data*)malloc(sizeof(data)); temp->nLow = p + 1; temp->nHigh = length - 1; Stack.push(temp); while(!Stack.empty()) { temp = Stack.top(); Stack.pop(); p = Partition(vect , temp->nLow , temp->nHigh); if(p > temp->nLow) //不是指向一处 还可以分下去 左边 { newdata = (data*)malloc(sizeof(data)); newdata->nLow = temp->nLow; newdata->nHigh = p - 1; Stack.push(newdata); } if(p < temp->nHigh) { newdata = (data*)malloc(sizeof(data)); newdata->nLow = p + 1; newdata->nHigh = temp->nHigh; Stack.push(newdata); } } } template<typename T> void show(vector<T> vect) { for(vector<T>::iterator v_it = vect.begin(); v_it != vect.end(); ++v_it) { cout << *v_it << " "; } printf("\n"); } int main() { vector<int> vect(10 , 9); //= {6 , 4 , 2 , 5 , 45 , 23 , 23 , 54 , 29}; quicksort(vect); show(vect ); }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/u011185633/article/details/47093261