数组工具类Java.util.Arrays

1、数组反转

主要思路:定义一个中间变量,将需要替换的两个数组的值进行交换

public class Demo1 {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5, 6};
        reverse(array);
        System.out.println(Arrays.toString(array));
    }
    public static void reverse(int[] array) {
        int temp;
        for (int i = 0; i < array.length / 2; i++) {
            temp = array[array.length - 1 - i];
            array[array.length - 1 - i] = array[i];
            array[i] = temp;
        }
    }
}

2、冒泡排序

主要思路:定义一个中间变量,第一遍循环找出最大的放在数组末尾,第二遍循环找出第二大的数组放在数组倒数第二位,以次类推,可以得出一个排好序的数组。时间复杂度为O(n2)

public class Demo2 {
    public static void main(String[] args) {
        int[] arrays = {8,1,7,2,6,3,5,4};
        sort(arrays);
        System.out.println(Arrays.toString(arrays));
    }
    public static void sort(int[] arrays){
        int temp = 0;
        for (int i = 0; i < arrays.length; i++) {
            for (int j = 0; j < arrays.length-1; j++) {
                if(arrays[j] > arrays[j+1]){
                    temp = arrays[j];
                    arrays[j] = arrays[j+1];
                    arrays[j+1] = temp;
                }
            }
        }
    }
}
posted @ 2021-12-01 23:27  吃辣椒会上瘾  阅读(27)  评论(0编辑  收藏  举报