数组简单排序

java对数组排序进行封装Arrays.sort() 里面进行了快速排序。手动实现一下数组的简单排序

冒泡排序 插入排序 选择排序

package arrays.simples.sort;

public class SimpleSort {

    /**
     * 数组冒泡排序
     */
    public static int[] bubbleSort(int[] arrays) {
        for (int i = 0; i <= arrays.length; i++) {
            boolean flag = true;
            for (int j = 0; j < arrays.length - 1; j++) {
                if (arrays[j] > arrays[j + 1]) {
                    int temp = arrays[j];
                    arrays[j] = arrays[j + 1];
                    arrays[j + 1] = temp;
                    flag = false;
                }
            }
            if (flag) { // 已顺序
                break;
            }
            System.out.print("第" + (i + 1) + "轮遍历:");
            for (int value : arrays) {
                System.out.print(value);
            }
            System.out.println();
        }
        return arrays;
    }

    /**
     * 插入排序
     */
    public static int[] insertSort(int[] arrays) {
        int insert = 0;
        for (int i = 0; i < arrays.length; i++) {
            insert = arrays[i]; // 要插入的值
            int j = 0;
            for (j = i; j > 0 && insert <= arrays[j - 1]; j--) {
                arrays[j] = arrays[j - 1];
            }
            arrays[j] = insert;
        }
        return arrays;
    }

    /**
     * 选择排序
     */
    public static int[] selectSort(int[] arrays) {
        int minTemp = 0;  //  存储最小值
        for (int i = 0; i < arrays.length - 1; i++) {
            for (int j = i + 1; j < arrays.length; j++) {
                if (arrays[i] > arrays[j]) {
                    minTemp = arrays[j];
                    arrays[j] = arrays[i];
                    arrays[i] = minTemp;
                }
            }
            System.out.print("第" + (i + 1) + "轮遍历:");
            for (int value : arrays) {
                System.out.print(value);
            }
            System.out.println();
        }
        return arrays;
    }

}

测试类

package arrays;

import arrays.simples.sort.SimpleSort;

public class Test {
    
    public static void main(String[] args) {
        int[] arrays = {5, 4, 9, 6, 3, 7, 1, 8, 2};
        // 冒泡排序
        // arrays = SimpleSort.bubbleSort(arrays);
        // 选择排序
        // arrays = SimpleSort.selectSort(arrays);
        // 插入排序
        arrays = SimpleSort.insertSort(arrays);
        for (int value : arrays) {
            System.out.print(value + " ");
        }
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值