1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| import java.time.Duration; import java.time.LocalTime; import java.util.Arrays;
public class BubbleSort { public static void main(String[] args) {
int[] arr = {9, 6, 1, 5, 4, 7, 8, 3, 2}; System.out.println("原数组:"+Arrays.toString(arr)); bubbleSort(arr, arr.length); System.out.println("外循环控制循环次数!"); System.out.println("排序后:"+Arrays.toString(arr)); System.out.println("---------------------------------");
int[] array1 = {95, -2, 1, -5, 4, 97, -8, 3, 2}; int[] array = {1,2,3,4,5,6,7}; System.out.println("原数组:"+Arrays.toString(array)); inBubbleSort(array); System.out.println("-----inBubbleSort------"); System.out.println(Arrays.toString(array));
System.out.println("-----testInBubbleSort------"); int[] testArray = new int[80000]; for (int i = 0; i <80000 ; i++) { testArray[i] = (int) (Math.random() * 800000); }
LocalTime start = LocalTime.now(); System.out.println("开始时间为:"+start);
inBubbleSort(testArray);
LocalTime end = LocalTime.now(); System.out.println("结束时间为:"+end);
Duration time = Duration.between(start, end); System.out.println("时间为:"+time.toMillis()+" 毫秒!"); }
public static void inBubbleSort(int[] array){ int count = 0; int temp = 0; boolean flag = false;
for (int i = 0; i < array.length - 1; i++) { for (int j = 0; j < array.length - 1 - i; j++) { if (array[j] > array[j + 1]) { count++; flag = true; temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } }
if(!flag){ break; }else { flag = false; } } System.out.println("交换次数:"+count); }
public static void bubbleSort(int[] arr, int length) {
for (int j = length; j >= 1; j--) { bubble(arr, length); } }
public static void bubble(int[] arr, int length) { int temp; for (int i = 0; i < length - 1; i++) { if (arr[i] > arr[i + 1]) { temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; } } } }
|