栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java之快速排序代码

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java之快速排序代码

快速排序

快速排序代码
	将最后一位作为准参数,分为两块,大于准参数的放在右边,小于准参数的放在左边,再从每一块中将最后一个作为准参数,以此类推进行。直接看代码
public class QuickSort {

    public static void main(String[] args) {
    }

    @Test
    public void test (){
    	// 当最后一位数是最小值或者最大值时,需要做一些特殊处理
        int[] arr = {4,8,2,1,6,7,5,9,10};
		// 随机选取准参数
 		int a =  (int)(Math.random()*(arr.length));
        System.out.println("a:" +a);;
        QuickSort(arr,0,a);
        // int a = 5;
        // QuickSort(arr,0,arr.length-1);
        print(arr);
    }

    public int Partition(int[] arr,int low,int high){
        // 获取基准数
        int piv = arr[high];
        int left = low;
        int right = high - 1;
        while (left < right){
            while (left <= right && arr[left] <= piv ){
                left++;
            }
            while (left <= right && arr[right] >=piv){
                right--;
            }
            if (left < right){
                swap(arr,left,right);
            }
        }
        if (arr[high] > arr[left]){
            return left;
        }
        swap(arr,left,high);
        return left;
    }

    public void QuickSort (int[] arr ,int low,int high) {
        if (low < high){
            int p = Partition(arr,low,high);
            QuickSort(arr,low,p-1);
            QuickSort(arr,p+1,high);
        }
        // 随机获取准参数时,后面一段的处理 或者以第一值为准参数时 
        else if (low == high && low <= arr.length){
            int p = Partition(arr,low,arr.length-1);
            QuickSort(arr,low,p-1);
            QuickSort(arr,p+1,arr.length-1);
        }
    }

    public static void swap(int[] arr, int i, int j){
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public static void print(int[] arr){
        for (int i : arr) {
            System.out.print(i + " ");
        }
    }
}

结果如下: 每次选择的准参数不同,产生的结果相同


发现了一个bug

改良后的代码

    public void QuickSort (int[] arr ,int low,int high) {
        if (low < high){
            int p = Partition(arr,low,high);
            if (p ==0){
                QuickSort(arr,0,0);
            } else {
                QuickSort(arr,low,p-1);
                QuickSort(arr,p+1,high);
            }
        } else if (low == high && low <= arr.length){
            lToR(arr,low,arr.length - 1);
        }
    }

    public void lToR (int[] arr ,int low,int high){
        if (low < high) {
            int p = Partition(arr, low, high);
            lToR(arr, low, p - 1);
            if (p != arr.length) {
                lToR(arr, p + 1, high);
            }
        }
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/667460.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号