package demo;
/**
* 冒泡排序及其优化;
* 稳定排序;
* 时间复杂度为O(n^2)
*
* @author Lynn
*
*/
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {10,9,8,7,6,5,4,3,2,1};
int[] arr1 = {1,2,3,4,5,6,7,8,9,10};
int[] arr2 = {1,2,3,4,5,6,7,8,9,10};
sort2(arr); //使用二种方法;
printArr(arr);
sort1(arr1);
printArr(arr1);
sort2(arr2);
printArr(arr2);
}
/**
* 常规排序(下沉);
*
* @param arr
* @return
*/
private static void sort1(int[] arr) {
int count = 0;
for (int i = 0; i < arr.length-1; i++) { //趟数,如果有10个数则需要9趟比较完;
count++;
for (int j = 0; j < arr.length-1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = temp;
}
}
}
System.out.println("调用sort1:"+count);
}
/**
* 优化
*
* @param arr
*/
public static void sort2(int[] arr) {
int count = 0;
boolean flag = true;// 是否存在交换;
for (int i = 0; i < arr.length-1 && flag; i++) {
count++;
flag = false;// 初始化为false;
for (int j = 0; j + 1 < arr.length - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = temp;
flag = true;//出现了交换;
}
}
}
System.out.println("调用sort2:"+count);
}
private static void printArr(int[] arr) {
for(int i:arr) {
System.out.print(i+" ");
}
System.out.println();
}
}
运行结果