- 每進行一次氣泡排序,就把最大的數放在最後面
- 這樣下一次排序,就可以少進行一次比較
- 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;
}
}
}
}