首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >QuickSearch快排

QuickSearch快排

作者头像
爱撸猫的杰
发布2020-09-22 10:22:35
4280
发布2020-09-22 10:22:35
举报
文章被收录于专栏:爱撸猫的杰爱撸猫的杰
import java.util.Scanner;

/**
 * @program:
 * @description:
 * @author: Jay
 * @create: 2020-09-21 19:23
 **/
public class QuickSearch {
    public static void QKsort(int[] arr, int low, int high) {
        if (low < high) {
            int pos = QKpass(arr, low, high);    //划分两个子表
            QKsort(arr, low, pos - 1);            //对左子表快排
            QKsort(arr, pos + 1, high);            //对右子表快排
        }
    }

    /**
     * 一趟快速排序算法
     *
     * @param arr 待排序数组
     * @param low 数组开始下标
     * @param
     * @return
     */
    public static int QKpass(int[] arr, int low, int high) {
        int temp = arr[low];        //先把当前元素作为待排值(一趟排序实际上就是把它放到合适的位置)
        while (low < high) {
            while (low < high && arr[high] >= temp)    //从右向左扫描,找到第一个小于temp的值
            {
                high--;
            }
            if (low < high) {                        //将此值放入下标为low的数组中
                arr[low] = arr[high];
                low++;
            }
            while (low < high && arr[low] <= temp)    //从左向右扫描找到第一个大于temp的值
            {
                low++;
            }
            if (low < high) {
                arr[high] = arr[low];                //放在下标为high的数组中
                high--;
            }
        }
        arr[low] = temp;                            //将此元素放入其准确位置
        return low;                                    //返回此次排序完成的值当前下标(即此位置的元素已经排好)
    }

    public static void main(String[] args) {
        int[] arr = new int[10];
        Scanner sc = new Scanner(System.in);
        for (int i = 0; i < arr.length; i++) {
            arr[i] = sc.nextInt();
        }
        sc.close();
        QKsort(arr, 0, arr.length - 1);
        for (int x : arr) {
            System.out.print(x + " ");
        }
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-09-21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档