递归和非递归快排

#include
#include
using namespace std;

//快排
int Partion(int *arr, int beg, int end)
{
    if(arr==NULL)
    {
        exit(-1);
    }
    int tep = arr[beg];
    while(begwhile(begif(begwhile(beg=arr[beg])
        {
            beg++;
        }
        if(begreturn beg;
}
void QuickSort(int *arr , int beg, int end)
{
    if(arr==NULL)
    {
        return;
    }
    if(begint mid = Partion(arr , beg , end);
        QuickSort(arr , beg , mid-1);
        QuickSort(arr , mid+1, end);
    }
}
//非递归快排,其实就用一个栈保存每次的Partion()的返回值,
void _QuickSort(int *arr , int beg, int end)
{
    stack<int> s;
    if(begint mid = Partion(arr , beg , end);
        {
            if(beg1)
            {
                s.push(beg);
                s.push(mid-1);
            }
            if(mid+11);
                s.push(end);
            }
        }
    }
    while(!s.empty())
    {
        int q = s.top();
        s.pop();
        int p = s.top();
        s.pop();
        int mid = Partion(arr , p, q);
        if(p1)
        {
            s.push(p);
            s.push(mid-1);
        }
        if(mid+11);
            s.push(q);
        }
    }
}
int main()
{
    int arr[] = {9,8,7,6,5,4,3,2,1,89,78,9999,8};
    int len = sizeof(arr)/sizeof(arr[0]);
    _QuickSort(arr, 0 , len-1);
    for(int i=0;icout<" ";
    }
    cout<return 0;
}

你可能感兴趣的:(数据结构)