package com.hao.firstdemo.datastruct.sort;
/**
* @author haoxiansheng
* @data 2020/5/7
*/
public class BubbleSort {
public static void main(String[] args) {
int [] arr = {1, 6, 10, 7, 4};
int [] res = sort(arr);
for (int i = 0; i < res.length; i++) {
System.out.print(res[i] + "\t");
}
//可以測試一下兩個比較的速度 用隨機數 生成多一些數據
// 加運行時間比較 Instant 打印就知道
}
/**
* 從小到大排列 時間複雜度O(n^2)
* @param arr
* @return
*/
public static int [] sort(int [] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int temp = 0; //臨時遍量
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j+1]) {
temp = arr[j+1];
arr[j+1] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
/**
* 從小到大排列 優化 減少比較次數
* @param arr
* @return
*/
public static int [] sortTwo(int [] arr) {
boolean flag = false; //標識
for (int i = 0; i < arr.length - 1; i++) {
int temp = 0; //臨時遍量
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j+1]) {
flag = true;
temp = arr[j+1];
arr[j+1] = arr[j];
arr[j] = temp;
}
}
if (!flag) {
break; //在一趟排序中, 一次交換都沒有發生過
} else {
flag = false; //重置flag, 進行下次判斷
}
}
return arr;
}
}