• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Y-wee
博客园    首页    新随笔    联系   管理     

Java快速排序

Java快速排序

/**
 * 快速排序
 *
 * @author yl
 */
public class QuickSort {

    public static void main(String[] args) {
        int[] array = {7, 6, 9, 3, 1, 5, 2, 4};
        System.out.println(Arrays.toString(quickSort(array,0,array.length-1)));
    }

    /**
     * 快速排序算法
     * 参考:https://blog.csdn.net/morewindows/article/details/6684558、https://blog.csdn.net/shujuelin/article/details/82423852
     * @param array
     * @param left
     * @param right
     * @return
     */
    public static int[] quickSort(int[] array,int left,int right) {
        if (left>right){
            return array;
        }

        // 将第一个数作为基准数
        int baseNum = array[left];
        // 左边数的下标
        int leftIndex=left;
        // 右边数的下标
        int rightIndex=right;

        while (leftIndex < rightIndex) {
            // 从右边开始找第一个小于基准数的数的下标
            while (leftIndex < rightIndex && array[rightIndex] >= baseNum) {
                rightIndex--;
            }
            // 从左边开始找第一个大于基准数的数的下标
            while (leftIndex < rightIndex && array[leftIndex] <= baseNum) {
                leftIndex++;
            }
            // 将找到的数左右互换
            if (leftIndex<rightIndex){
                int temp=array[leftIndex];
                array[leftIndex]=array[rightIndex];
                array[rightIndex]=temp;
            }
        }

        // 当左边下标等于右边下标时,将基准数和该下标对应数互换
        array[left]=array[leftIndex];
        array[leftIndex]=baseNum;

        // 递归调用
        quickSort(array,left,rightIndex-1);
        quickSort(array,rightIndex+1,right);

        return array;
    }

}
记得快乐
posted @ 2021-11-18 16:55  Y-wee  阅读(208)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3