package com.guangyunl.f_array; import java.util.Random; import java.util.Scanner; // 数组的冒泡排序 // 冒泡排序法是采用数组中相邻元素进行比较换位 public class Demo02Bubble { public static void main(String[] args) { Demo02Bubble demo02Bubble = new Demo02Bubble(); // 输入创建数组的长度 System.out.print("请输入要创建的数组的长度:"); Scanner scanner = new Scanner(System.in); int arrLength = scanner.nextInt(); // 创建数组 int[] arr1 = createArray(arrLength); // 输出数组 System.out.print("排序前"); demo02Bubble.printArray(arr1); // 给数组排序 arr1 = bubbleSort(arr1); // 输出数组 System.out.print("排序后"); demo02Bubble.printArray(arr1); } // 创建数组 public static int[] createArray(int n){ int[] arr1 = new int[n]; // 通过随机数生成数组的值 Random random = new Random(); for (int i = 0; i < arr1.length; i++) { // 随机生成0~99的数作为数组的值 arr1[i] = random.nextInt(100); } return arr1; } // 给数组排序 冒泡排序 // 将数组中的元素按照大小进行排序,默认都是以升序的形式进行排序 public static int[] bubbleSort(int[] arr){ int temp = arr[0]; for (int i = 0; i < arr.length-1; i++) { for (int j = 0; j < arr.length-1-i; j++) { if(arr[j] > arr[j+1]){ temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } return arr; } // 输出数组 (非静态方法,得new,对象点方法名 调用) public void printArray(int[] arr){ for (int i = 0; i < arr.length; i++) { if (i == 0){ System.out.print("数组为 = [ " + arr[i] + ", "); }else if(i == arr.length-1){ System.out.println(arr[i] + " ]"); }else{ System.out.print(arr[i] + ", "); } } } } /* 请输入要创建的数组的长度:11 排序前数组为 = [ 43, 22, 18, 3, 24, 59, 99, 24, 13, 59, 36 ] 排序后数组为 = [ 3, 13, 18, 22, 24, 24, 36, 43, 59, 59, 99 ] */
冒泡排序(JAVA)
于 2024-12-18 13:26:36 首次发布