package class01; import java.util.Arrays; /** * 冒泡排序 * 概述:每相邻的2个数比较,较大的数向后交换。排到最后一个位置时,它就是整个数组的最大值,第一轮结束。 * 继续从第0位置和第1位置的2个数比较。周而复始。 */ public class Code02_BubbleSort { public static void bubbleSort(int[] arr) { if (arr == null || arr.length < 2) { return; } for (int i = arr.length - 1; i > 0; i--) { for (int j = 0; j < i; j++) { if (arr[j] > arr[j + 1]) { swap(arr, j, j + 1); } } } } public static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } public static void printArr(int[] arr) { for (int i : arr) { System.out.print(i + " "); } System.out.println(); } public static int[] generateRandomArr(int maxValue, int maxLength) { int[] arr = new int[(int) (Math.random() * maxLength)]; for (int i = 0; i < arr.length; i++) { arr[i] = (int) (Math.random() * maxValue); } return arr; } public static int[] copyArr(int[] arr1) { int[] arr2 = new int[arr1.length]; for (int i = 0; i < arr1.length; i++) { arr2[i] = arr1[i]; } return arr2; } public static void main(String[] args) { int maxValue = 100; int maxLen = 10; int testTimes = 10; for (int i = 0; i < testTimes; i++) { int[] arr1 = generateRandomArr(maxValue, maxLen); int[] arr2 = copyArr(arr1); int[] arr3 = copyArr(arr1); Arrays.sort(arr2); bubbleSort(arr1); boolean equals = isEquals(arr1, arr2); if (!equals) { System.out.println("oops!"); System.out.println("arr1 = " + Arrays.toString(arr1));//自己实现的冒泡排序。 System.out.println("arr2 = " + Arrays.toString(arr2));//工具类排好序的。 System.out.println("arr3 = " + Arrays.toString(arr3));//原数组,还没有排序。 return; } } System.out.println("nice!"); } private static boolean isEquals(int[] arr1, int[] arr2) { if (arr1 == null && arr2 != null) { return false; } if (arr2 == null && arr1 != null) { return false; } if (arr1 == null && arr2 == null) { return true; } if (arr1.length != arr2.length) { return false; } for (int i = 0; i < arr1.length; i++) { if (arr1[i] != arr2[i]) { return false; } } return true; } }
标签:arr,return,int,冒泡排序,length,arr2,arr1 From: https://www.cnblogs.com/TheFloorIsNotTooHot/p/16838625.html