2. Bubble Sort

bubble ['bʌbl] n. bubble v. bubbling

Bubble sort: Large numbers bubble to the end of the array like bubbles.

∵ The determined number (sorted number) is behind
∴ In a new round, j = 0 / j = 1 (traverse from the very beginning)

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);
        }
    }
}

or

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);
        }
    }
}

Guess you like

Origin blog.csdn.net/m0_60641871/article/details/129165409