zoukankan      html  css  js  c++  java
  • 快速排序

    快速排序

    快速排序的思路:

    1. 找到基准数据(一般找数组的第一个位置)

    2. 对这个数组进行分析,将比基准数据小的放到左侧,比基准数据大的放到右侧

    3. 找到基准数据所在的坑,然后分析基准数据两侧的数组,重复上面的步骤

    对于一个数组{21,32,43,97,21,5,66}

    选择21为基础值,比较21与最右侧的值的大小,一步一步移动high游标

    到达右侧第二个位置,可以看出5比21小,小的都要移动到左侧

    从左往右比较,开始移动左侧的low游标,比较与base,如果大于base交换

    开始移动high游标,找比base值小的

     

    这样一次位置就找好了,21左侧都是比他小的,右侧都是比他大的,分别对左右两侧进行相似的过程

    程序实例如下:

    public class QuickSort{
        public static void main(String[] args){
            int[] arr =new int[10];
            System.out.print("原数组为:");
            for(int i = 0;i<10;i++){
                double temp = 100*Math.random();
                arr[i] =(int)temp;
                System.out.print(arr[i] + " ");
            }
            System.out.println();
            System.out.print("排序后的数组为:");
    
            quickSort(arr,0, arr.length - 1);
            for(int i =0 ;i<= arr.length - 1;i++){
                System.out.print(arr[i]+ " ");
            }
        }
    
        public static void quickSort(int[] arr, int low, int high){
            if(low >= high) {
                return;
            }
            int division = quick(arr, low, high);
            quickSort(arr, low, division - 1);
            quickSort(arr, division + 1, high);
        }
    
        public static int quick(int[] arr, int low , int high){
            while(low < high){
                while(low < high && arr[low] < arr[high]){
                    high--;
                }
                swap(arr, low, high);
                while(low < high && arr[low] < arr[high]){
                    low++;
                }
                swap(arr, low, high);
            }
            return low;
        }
    
        public static void swap(int[] arr, int low, int high){
            int temp = arr[low];
            arr[low] = arr[high];
            arr[high] = temp;
        }
    }
    

      

  • 相关阅读:
    Mongo Windows 基本使用入门
    ASP.NET Web API 使用Swagger使用笔记
    Smtp协议与Pop3协议的简单实现
    详解boost库中的Message Queue .
    Bencode编码解析的C++实现
    pugixml使用教程
    在QT中使用Irrlicht引擎的方法与步骤
    七大查找算法
    java保留小数点两位的4种方法
    [Node] nvm 安装 node 和 npm
  • 原文地址:https://www.cnblogs.com/zhangchiblog/p/8660087.html
Copyright © 2011-2022 走看看