一, 向上冒泡排序
元素从底向上冒,最轻的冒到最上边,最沉的冒到最下边。
时间复杂度为O(N^2)
证明如下
first element compare N-1
second element compare N-2
...
last element compare 0
total compares: [(0+1+...+N-1)*N]/2=(N^2)/2
实施代码
public static void bubbleSortUp(int[] array) {
for (int i = 0; i < array.length; i++) {
for (int j = array.length - 1; j > i; j--) {
if (more(array[j - 1], array[j]))
exchange(array, j, j - 1);
}
}
}
compare and exchange
// compare
public static boolean more(int v, int w) {
return v > w;
}
// exchange
public static void exchange(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
二,向下冒泡排序