打赏
Fork me on GitHub

快排

package mytest;

import java.util.Arrays;

/**
 * @author :l_coil
 * @date :2021/12/11 9:41 下午
 */
public class QuickSort {

    public static void main(String[] args) {
        int[] ints = {3, 1, 4, 8, 7, 5, 2};
        int[] result = quickSort(ints,0,6);
        System.out.println(Arrays.toString(result));
    }
    public static int[] quickSort(int[] arr, int l, int r) {

        // 确定一次运算的基准值
        int base = arr[l];
        int lindex = l, rindex = r;
        while (lindex < rindex) {
            // 从右至左找到第一个小于基准值的位置
            while (arr[rindex] > base && lindex < rindex) {
                rindex--;
            }
            // 从左至右找到第一个大于基准值的位置
            while (arr[lindex] < base && lindex < rindex) {
                lindex++;
            }

            // 处于中间位置,一轮运算暂未结束,进行交换
            if (lindex < rindex && arr[lindex] != arr[rindex]) {
                int temp = arr[rindex];
                arr[rindex] = arr[lindex];
                arr[lindex] = temp;
            }
            //向右移动左值指针,或者向左移动右指针都阔以
            if (lindex < rindex && arr[lindex] == arr[rindex]) {
                lindex++;
            }
        }

        // 分治前一轮的再排序
        if (l < lindex - 1) {
            arr = quickSort(arr, l, lindex - 1);
        }
        if (rindex + 1 < r) {
            arr = quickSort(arr, rindex + 1, r);
        }

        return arr;
    }
}

  

posted @ 2021-12-12 10:33  l-coil  阅读(39)  评论(0编辑  收藏  举报