交换排序之 冒泡排序与快速排序

冒泡排序进行了flag标识,略微提高了排序效率;

快速排序使用递归实现

两种排序算法实现均可以传入规定排序范围的参数以实现局部有序。

import java.util.Random;

public class ComparisonSortingAlgorithm {
    public static void main(String[] args) {
        Integer[] array = new Integer[10];
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            array[i] = random.nextInt(100);
            System.out.print(array[i] + "\t");
        }
        System.out.println();
//        bubbleSort(array,0,array.length-1);
        quickSort(array, 0, array.length - 1);
        for (int i = 0; i < 10; i++) {
            System.out.print(array[i] + "\t");
        }
    }

    public static <T extends Comparable> void bubbleSort(T[] array, int low, int high) {
        if (low < 0 || high > array.length - 1) {
            throw new RuntimeException("The sort range is not set properly.");
        }
        for (int i = high - low; i > 0; i--) {
            boolean isExchange = false; //排序过程中是否发生交换,若一轮排序过后未发生交换,直接结束排序过程
            for (int j = 0; j < i; j++) {
                if (isLes(array, j + 1, j)) {
                    exc(array, j, j + 1);
                    isExchange = true;
                }
            }
            if (!isExchange) return;
        }
    }

    public static <T extends Comparable> boolean isLes(T[] array, int i, int j) {//比较数组中两个元素的大小
        return array[i].compareTo(array[j]) < 0;
    }

    public static <T> void exc(T[] array, int i, int j) {//对数组中的元素进行交换
        T temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }


    public static <T extends Comparable> int partition(T[] array, int low, int high) {
        T pivot = array[low];
        while (low < high) {
            while (low < high && array[high].compareTo(pivot) >= 0)
                high--;
            array[low] = array[high];
            while (low < high && array[low].compareTo(pivot) <= 0)
                low++;
            array[high] = array[low];
        }
        array[low] = pivot;
        return low;
    }

    public static <T extends Comparable> void quickSort(T[] array, int low, int high) {
        if (low<0||high>array.length-1){
            throw new RuntimeException("The sort range is not set properly.");
        }
        if (low < high) {
            int pivotIndex = partition(array, low, high);
            quickSort(array, low, pivotIndex - 1);
            quickSort(array, pivotIndex + 1, high);
        }
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值