快速排序 Quick Sort

 

// low is the first index and high is the last index in the array
int Rico_partition(int* arr, int low, int high)
{
    //使用while循环,最终low与high会合(low==high)
    while (low < high)
    {
        //取下标为low的作为中心值
        int temp = arr[low];
        //从后往前进行比较,知道当前记录的排序码小于等于中心值
        while (low<high && arr[high]>=temp) high--;
        if (low <high)
        {
            //将排序码小于等于中心值的记录
            //交换到前面当前空出的记录位置
            arr[low++] = arr[high];//把后的付给前的
        }
        //从前往后
        while (low<high && arr[low]<=temp) low++;
        if (low < high)
        {
            arr[high--] = arr[low];
        }
        //找到中心值对应的记录所在的位置,写入中心值对应的记录
        arr[low] = temp;
    }

    return low;
}

void QSort(int* arr, int low, int high)
{
    if (low >= high) return;

    /*int pivot = Rico_partition(arr, low, high);
    QSort(arr, low, pivot-1);
    QSort(arr, pivot+1, high);*/

    while(low < high) //此处用循环(用于改变low后,处理右边的子记录集)
    {
        int pivot = Rico_partition(arr, low, high);
        //递归处理排序码小于中心值的 子记录集(左边的)
        QSort(arr, low, pivot-1);
        //实际上上面处理完左边的子记录集后,low已经没用了,
        //所以可以利用low,改变low的值为 右边的子记录集的开始下标,对右边的子记录集进行排序
        low = pivot+1; //  利用low,大大减少堆栈深度!!! 从递归变为了迭代!
    }
}

 

posted on 2013-03-01 23:58  Rico Huang  阅读(148)  评论(0编辑  收藏  举报

导航