bubble ['bʌbl] n.气泡 v.冒泡
冒泡排序:大的数像 冒泡 一样冒到数组的最后。
∵ 确定的数(排好序的数)在后面
∴ 在新的一轮,j = 0 / j = 1(从最开始往后遍历)
public static void bubbleSort(int[] nums) {
for (int i = 0; i < nums.length; i++) {
for (int j = 1; j < nums.length - i; j++) {
//∵ j-1 >= 0,∴ j = 1
if (nums[j - 1] > nums[j]) swap(nums, j - 1, j);
}
}
}
或
public static void bubbleSort(int[] nums) {
for (int i = 0; i < nums.length - 1; i++) {
for (int j = 0; j < nums.length - i - 1; j++) {
//∵ j+1 < len,∴ j < nums.length-i-1
if (nums[j] > nums[j + 1]) swap(nums, j, j + 1);
}
}
}