快速排序

此方法学习了别人的算法,感觉清晰明了了很多。

package sort;

public class quickSortDemo {

    public static void main(String[] args) {
        int[] arr = new int[]{101, 34, 119, 1, 52, 38, 67, 96, 23, 15, 2, 111};
        quickSort(arr, 0, arr.length - 1);
        for (int i : arr) {
            System.out.print(i+",");
        }
        System.out.println();
    }

    private static void quickSort(int[] arr, int low, int high) {
        if (low < high) {
            //找寻基准数据的正确索引
            int index = getIndex(arr, low, high);

            quickSort(arr, low, index - 1);
            quickSort(arr, index + 1, high);
        }
    }

    private static int getIndex(int[] arr, int low, int high) {
        //基准数据
        int temp = arr[low];
        while (low < high) {
            //当队尾的元素大于等于基准数据时,向前挪动high指针
            while (arr[high] >= temp && low < high) {
                high--;
            }
            //如果队尾元素小于tmp,需要将其赋值给low
            arr[low] = arr[high];

            //当队首的元素小于等于基准数据时,向后挪动high指针
            while (arr[low] <= temp && low < high) {
                low++;
            }
            //如果队尾元素小于tmp,需要将其赋值给low
            arr[high] = arr[low];
        }
        //跳出循环时,low和high相等,此时的low或者high就是tmp的正确索引位置
        //但是此时的Low的位置的值并不是tmp,所以需要将tmp赋值给arr。
        arr[low] = temp;
        return low;
    }
}

参考的文章链接:https://blog.csdn.net/nrsc272420199/article/details/82587933
https://wiki.jikexueyuan.com/project/easy-learn-algorithm/fast-sort.html

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容