冒泡排序的原理是一直比較相鄰的兩個(gè)數(shù)的值稿壁,如果左邊比右邊位置的值要大,則將這兩個(gè)位置的值互換奥秆。當(dāng)?shù)谝惠喲h(huán)完成逊彭,最大值將在數(shù)組最右邊;當(dāng)?shù)诙喲h(huán)完成构订,數(shù)組第二大的值會(huì)在數(shù)組倒數(shù)第二的位置侮叮,以此類推。
冒泡排序的平均時(shí)間復(fù)雜度為O(n^2)悼瘾, 最好的時(shí)間復(fù)雜度為O(n)囊榜,最壞時(shí)間復(fù)雜度為O(n^2)。
/**
* Created by lkmc2 on 2018/1/8.
*/
public class BubbleSort {
public static void bubbleSort(int[] array) {
for (int i = 0; i < array.length - 1; i++)
for (int j = 0; j < array.length - i - 1; j++)
//如果第j個(gè)元素比j+1元素的值大
if (array[j] > array[j + 1]) {
//交換這兩個(gè)元素
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
public static void main(String[] args) {
int[] array = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
bubbleSort(array);
for (int num : array) {
System.out.print(num + " ");
}
}
}
運(yùn)行結(jié)果