快排非递归实现

来源:互联网 发布:大数据毕业摄影 编辑:程序博客网 时间:2024/05/29 17:41

int partition(int* arr, int low, int high)

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


void non_recursive_qsort(int* arr, int low, int high)
{
    stack<int> s;
    int pivot;
    if(low < high)
        return ;
    pivot = partition(arr, low, high)
    if(low < pivot - 1)
    {
        s.push(low);
        s.push(pivot - 1);
    }
    if(high > pivot + 1)
    {
        s.push(high);
        s.push(pivot + 1);
    }
    //其实就是用栈保存每一个待排序子串的首尾元素下标,下一次while循环时取出这个范围,对这段子序列进行partition操作
    //如果pivot的左段或右段已经少于两个元素了,则无需再对这个子段partition了
    while(!s.empty())
    {
        high = s.top();
        s.pop();
        low = s.top();
        s.pop(); 
        pivot = partition(arr, low, high)
        if(low < pivot - 1)
        {
            s.push(low);
            s.push(pivot - 1);
        }
        if(high > pivot + 1)
        {
            s.push(high);
            s.push(pivot + 1);
        }
    }
}


0 0