每进行一次冒泡排序,就把最大的数放在最后面这样下一次排序,就可以少进行一次比较n个数,就需要排序n-1次优化冒泡排序,如果有一次一个变量的顺序也没有改变,那么直接结束这次循环即可
package com
.qin
.sort
;
import java
.lang
.reflect
.Array
;
import java
.text
.SimpleDateFormat
;
import java
.util
.Arrays
;
import java
.util
.Date
;
public class BubbleSort {
public static void main(String
[] args
) {
int arr
[] = {3,9,-1,10,20};
int arr1
[] = {3,9,-1,10,20};
int arr2
[] = {3,9,-1,10,20};
int temp
= 0 ;
for (int i
= 0; i
< arr
.length
-1; i
++) {
if (arr
[i
]>arr
[i
+1]){
temp
= arr
[i
+1];
arr
[i
+1] = arr
[i
];
arr
[i
] = temp
;
}
}
System
.out
.println("第一次排序完成后的数组");
System
.out
.println(Arrays
.toString(arr
));
for (int i
= 0; i
< arr
.length
-1-1; i
++) {
if (arr
[i
]>arr
[i
+1]){
temp
= arr
[i
+1];
arr
[i
+1] = arr
[i
];
arr
[i
] = temp
;
}
}
System
.out
.println("第二次排序完成后的数组");
System
.out
.println(Arrays
.toString(arr
));
for (int i
= 0; i
< arr1
.length
-1-1-1; i
++) {
if (arr
[i
]>arr
[i
+1]){
temp
= arr
[i
+1];
arr
[i
+1] = arr
[i
];
arr
[i
] = temp
;
}
}
System
.out
.println("第三次排序完成后的数组");
System
.out
.println(Arrays
.toString(arr
));
for (int i
= 0; i
< arr1
.length
-1-3; i
++) {
if (arr
[i
]>arr
[i
+1]){
temp
= arr
[i
+1];
arr
[i
+1] = arr
[i
];
arr
[i
] = temp
;
}
}
System
.out
.println("第四次排序完成后的数组");
System
.out
.println(Arrays
.toString(arr
));
System
.out
.println("=============================");
boolean flag
= false;
for (int i
= 0; i
< arr1
.length
-1; i
++) {
for (int j
= 0; j
< arr1
.length
-1-i
; j
++) {
if (arr1
[j
]>arr1
[j
+1]){
flag
= true;
temp
= arr1
[j
+1];
arr1
[j
+1] = arr1
[j
];
arr1
[j
] = temp
;
}
}
System
.out
.printf("第%d排序后",i
+1);
System
.out
.println(Arrays
.toString(arr1
));
if (!flag
){
break;
}else {
flag
= false;
}
}
System
.out
.println("====================");
bubbleSort(arr2
);
System
.out
.println("排序后");
System
.out
.println(Arrays
.toString(arr2
));
System
.out
.println("大规模测试");
int [] arr4
= new int [80000];
for (int i
= 0 ; i
< 80000 ; i
++){
arr4
[i
] = (int)(Math
.random() * 80000000);
}
Date date1
= new Date();
SimpleDateFormat simpleDateFormat
= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date1Str
= simpleDateFormat
.format(date1
);
System
.out
.println("排序前的时间是:"+date1Str
);
bubbleSort(arr4
);
Date date2
= new Date();
String date2Str
= simpleDateFormat
.format(date2
);
System
.out
.println("排序后的时间是:"+date2Str
);
}
public static void bubbleSort(int [] arr1
){
int temp
= 0 ;
boolean flag
= false;
for (int i
= 0; i
< arr1
.length
-1; i
++) {
for (int j
= 0; j
< arr1
.length
-1-i
; j
++) {
if (arr1
[j
]>arr1
[j
+1]){
flag
= true;
temp
= arr1
[j
+1];
arr1
[j
+1] = arr1
[j
];
arr1
[j
] = temp
;
}
}
if (!flag
){
break;
}else {
flag
= false;
}
}
}
}
结果