冒泡排序,升序。釋義參考百度百科
public static void bubbleSort(int[] nums) { for (int i = 0; i < nums.length; i++) { for (int j = i; j < nums.length; j++) { if (nums[i] > nums[j]) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } } } }
測試代碼:
import java.util.Arrays; public class BubbleSort { public static void main(String[] args) { int[] ints = {9, 12, 0, 5, -1}; bubbleSort(ints); System.out.println(Arrays.toString(ints)); } public static void bubbleSort(int[] nums) { for (int i = 0; i < nums.length; i++) { for (int j = i; j < nums.length; j++) { if (nums[i] > nums[j]) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } } } } }
測試待排序數組:
9, 12, 0, 5, -1
結果輸出:
[-1, 0, 5, 9, 12]