选择,冒泡,快排

本文展示了在Java中实现的快速排序、选择排序和冒泡排序算法,通过代码实例展示了如何对整数数组进行排序并打印结果。
摘要由CSDN通过智能技术生成
class Main {
    public static void main(String[] args) {
        int[] nums = {3, 4, 6, 1, 2, 4, 7};
        //quickSort(nums, 0, nums.length - 1);
        selectionSort(nums);
        //bubbleSort(nums);
        Arrays.stream(nums).forEach(x -> System.out.println("x = " + x));
        System.out.println();
    }

    //快排
    static void quickSort(int nums[], int start, int end) {
        if (start < end) {
            int l = start;
            int r = end;
            int base = nums[l];
            while (l < r) {
                while (l < r && nums[r] < base) {
                    r--;
                }
                nums[l] = nums[r];
                while (l < r && nums[l] > base) {
                    l++;
                }
                nums[r] = nums[l];
            }
            nums[l] = base;
            quickSort(nums, start, l - 1);
            quickSort(nums, l + 1, end);
        }
    }

    static void bubbleSort(int[] nums) {
        for (int i = 0; i < nums.length - 1; i++) {
            boolean flag = true;
            for (int j = 0; j < nums.length - i - 1; j++) {
                if (nums[j] > nums[j + 1]) {
                    int t = nums[j];
                    nums[j] = nums[j + 1];
                    nums[j + 1] = t;
                    flag = false;
                }
            }
            if (flag) {
                break;
            }
        }
    }

    static void selectionSort(int[] nums) {
        for (int i = 1; i < nums.length; i++) {
            int minIndex = i - 1;
            for (int j = i; j < nums.length; j++) {
                if (nums[j] < nums[minIndex]) {
                    minIndex = j;
                }
            }
            if (minIndex != i - 1) {
                int t = nums[i - 1];
                nums[i - 1] = nums[minIndex];
                nums[minIndex] = t;
            }
        }
    }
    
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值