快速排序递归及非递归实现

来源:互联网 发布:灰色关联分析软件 编辑:程序博客网 时间:2024/05/23 20:27

快速排序算法基于冒泡排序进行了改进,冒泡排序的效率为n^2,快速排序由于使用了分而治之的思想,将算法效率提高到了nlogn,常规实现快排的方式是递归实现,在实际的应用中,如果要进行排序的数据量比较大,使用递归的方式会出现问题,因此可以用非递归的方式来实现。
递归实现快速排序:
template
void quick_sort(T a[],int low,int high)
{
if(low > high)return;

int first = low;int last = high;T key = a[first];if(low <high){    while(first < last)    {        while(first<last && a[last] >=key)        {            last--;        }        a[first] = a[last];        while(first<last && a[first] <=key)        {            first++;        }        a[last] = a[first];    }    a[first] = key;    quick_sort(a,low,first-1);    quick_sort(a,first+1,high);}

}

非递归实现快速排序:
非递归的要点在于储存要排序数组首尾的两个编号,这里比较方便的是通过栈的方式储存。而排序的方式跟递归方式是相同的。代码如下:
实际对数组排序的过程:

template
int partion(T a[],int low,int high)
{
T pivot = a[low];

while(low < high){    while(low< high && a[high] >= pivot)        high--;    a[low] = a[high];    while(low<high && a[low] <= pivot)        low++;    a[high] = a[low];}a[low] = pivot;return low;

}

储存排序数组的位置及排序的过程:

template
void myunresort(T a[],int low,int high)
{
stack st;
if(low < high)
{
int mid = partion(a,low,high);

    if(low <mid-1)    {        st.push(low);        st.push(mid-1);    }    if(mid+1 <high)    {        st.push(mid+1);        st.push(high);    }    while(!st.empty())    {        int q = st.top();        st.pop();        int p = st.top();        st.pop();        mid = partion(a,p,q);        if(p<mid-1)        {            st.push(p);            st.push(mid-1);        }        if(q>mid+1)        {            st.push(mid+1);            st.push(q);        }    }}

}

0 0
原创粉丝点击