快速排序---改良的冒泡排序

快速排序是对于冒泡排序的改良

关于冒泡排序详见之前的博客:https://blog.csdn.net/szy2333/article/details/83118677

基本思想:

找一个数作为基数a,寻找这个基数的位置A,使位置A左边的元素的值均小于该基数a的值,该位置右边的元素的值军大于该基数a的值,然后以该基数a为准,将其左边的所有元素当做一个整体,并在这些元素中寻找一个基数b,寻找这个基数的位置B,使位置B左边的元素的值均小于该基数b的值,该位置右边的元素的值军大于该基数b的值(基数a右边和左边是一样的方法),然后不断迭代,直至每个元素左边的值都小于等于自己的值,右边的值都大于等于自己的值......使用递归的方式实现

图示过程:

watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3N6eTIzMzM=,size_16,color_FFFFFF,t_70

对于基数6的左边和右边分别使用同样的方法过程,将每边的第一个数作为基数,然后确定该基数的位置,过程如下

watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3N6eTIzMzM=,size_16,color_FFFFFF,t_70

继续上述方式,直至所有的数都到达自己正确的位置

代码如下:

排序代码

package 排序;

public class QuickSort {
    public static void quickSort(int[] array, int lowIndex, int highIndex) {
    		//得到基数位置
        int middleIndex = getMiddle(array, lowIndex, highIndex);
        //对于基数左边的元素递归该方法
        getMiddle(array, lowIndex, middleIndex - 1);
        //对于基数左边的元素递归该方法
        getMiddle(array, middleIndex + 1, highIndex);
    }

    public static int getMiddle(int[] array, int lowIndex, int highIndex) {
    		//将数组的第一个元素当做基数
        int tmp = array[lowIndex];
        //当lowIndex!=highIndex时,说明没有找到基数,则继续循环,调整位置
        while (lowIndex < highIndex) {  
        		//当基数小于等于以highIndex为下标的值时,highIndex不断左移
            while (lowIndex < highIndex && tmp <= array[highIndex]) {
                highIndex--;
            }
            //直至条件不成立,将array[highIndex]赋值给array[lowIndex]
            array[lowIndex] = array[highIndex];
						//当基数大于等于以lowIndex为下标的值时,lowIndex不断右移
            while (lowIndex < highIndex && tmp >= array[lowIndex]) {
                lowIndex++;
            }
            //直至条件不成立,将array[highIndex]赋值给array[lowIndex]
            array[highIndex] = array[lowIndex];
        }
        
        //循环结束,即找到基数的位置,此时将该基数位置的值赋值为最初的基数值
        array[lowIndex] = tmp;
        return lowIndex;
    }
}

测试代码

package 排序;

import static 排序.QuickSort.quickSort;

public class Test {
    public static void main(String[] args) {
        int[] array = new int[]{2, 9, 1, -5, 32, 31, 6, -5, 22, 0};
        quickSort(array, 0, array.length - 1);
        for(int i : array) {
            System.out.println(i);
        }
    }
}

 

 

 

 

 

 

 

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值