算法---快速排序

174 阅读2分钟

规则

第一轮:

  • 把0索引的数字作为基准数,确认基准数在数组中的正确问题.比基准数小的全部在左边,比基准数大的全部在右边
  • 寻找基准数位置的时候必须先从后往前找比基准数小的,再从前面往后找比基准数大的数字

后面循环重复第一轮即可

案例

int[] array = {6, 1, 4, 7, 9, 5, 3, 10, 2, 8};

quickSort(array, 0, array.length - 1);

//打印结果
for (int number : array) {
    System.out.print(number + " ");//1 2 3 4 5 6 7 8 9 10
}

//第一个参数: 指的是要查找的数组
//第二个参数: 指的是查找开始的索引
//第三个参数: 指的是查找的结束索引
public static void quickSort(int[] array, int startIndex, int endIndex) {
    //声明两个数值来记录要查找的范围
    int start = startIndex;
    int end = endIndex;

    if (start > end) {
        //递归的出口
        return;
    }
    //记录基准数
    int baseNumber = array[startIndex];

    //利用循环找到要交换的数字
    while (start != end) {
        //利用end,从后往前找比基准数小的数字
        while (true) {
            if (end <= start || array[end] < baseNumber) break;
            end--;
        }

        //利用start,从前面往后找比基准数大的数字
        while (true) {
            if (end <= start || array[start] > baseNumber) break;
            start++;
        }
        //将end和start指向的数字进行交换
        int temp = array[start];
        array[start] = array[end];
        array[end] = temp;
    }
    //当start和end指向同一数字的时候循环就会结束
    //此时表示已经找到了基准数在数组中存在的位置
    //然后进行基准数归位,也就是拿这个范围的第一个数字和start或者end指向数字进行交换
    int temp = array[startIndex];
    array[startIndex] = array[start];
    array[start] = temp;

    //上面是第一轮循环的结果,下面进行递归循环,直到所有数据排序完全
    //确认基准数左边的范围,重复上面的操作
    quickSort(array, startIndex, start - 1);
    //确认基准数右边的范围,重复循环
    quickSort(array, start + 1, endIndex);
}