排序之快速排序详解

思路:

 1、将一组需要排序的数中的第一个数作为准则

 2、对于剩余的数,如果小于该准则则放在该数的左边,否则放在它的右边

 3、对于该准则左边和右边的数分别再重复1、2

思考:

 1、需要使用辅助数组y来暂时存放已排好的数据

 2、需要使用a、b来记录需要排序的数据存放的位置编号范围,后面递归时需要用到

 3、需要使用c、d来记录数据存放在数组y中的哪个位置

 4、要将y中的数据复制回x的相应位置中,

 5、递归,递归结束的条件是a >= b

#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
int x[100];
int y[100];
void sort1(int *x, int *y, int a, int b);
int main()
{
    int n;
    while (cin >> n)
    {
        for (int i = 1; i <= n; i++)
            cin >> x[i];
        sort1(x, y, 1, n);
        for (int i = 1; i <= n; i++)
            cout << "  " << x[i];
        cout << endl;
    }
}

void sort1(int *x, int *y, int a, int b)
{
    if (a >= b)
        return;
    else
    {
        int c = a, d = b;
        int num = x[a];
        for (int i = a + 1; i <= b; i++)
        {
            if (x[i] < num)
            {
                y[c] = x[i];
                c++;
            }
            else
            {
                y[d] = x[i];
                d--;
            }
        }
        y[c] = num;
        for (int i = a; i <= b; i++)
            x[i] = y[i];
        sort1(x, y, a, c - 1);
        sort1(x, y, c + 1, b);
    }
}

 代码改进:

 不使用额外的存储空间,直接在原数组中进行调整;

代码借鉴
 * 排序的核心算法
     * 
     * @param array
     *      待排序数组
     * @param startIndex
     *      开始位置
     * @param endIndex
     *      结束位置
     */
    private void sortCore(int[] array, int startIndex, int endIndex) {
        if (startIndex >= endIndex) {
            return;
        }

        int boundary = boundary(array, startIndex, endIndex);

        sortCore(array, startIndex, boundary - 1);
        sortCore(array, boundary + 1, endIndex);
    }

    /*
     * 交换并返回分界点
     * 
     * @param array
     *      待排序数组
     * @param startIndex
     *      开始位置
     * @param endIndex
     *      结束位置
     * @return
     *      分界点
     */
    private int boundary(int[] array, int startIndex, int endIndex) {
        int standard = array[startIndex]; // 定义标准
        int leftIndex = startIndex; // 左指针
        int rightIndex = endIndex; // 右指针

        while(leftIndex < rightIndex) {
            while(leftIndex < rightIndex && array[rightIndex] >= standard) {
                rightIndex--;
            }
            array[leftIndex] = array[rightIndex];

            while(leftIndex < rightIndex && array[leftIndex] <= standard) {
                leftIndex++;
            }
            array[rightIndex] = array[leftIndex];
        }

        array[leftIndex] = standard;
        return leftIndex;
    }

部分内容来自http://blog.csdn.net/lemon_tree12138/article/details/50622744

posted @ 2018-02-16 22:19  hui666  阅读(188)  评论(0)    收藏  举报