共計(jì) 606 個(gè)字符,預(yù)計(jì)需要花費(fèi) 2 分鐘才能閱讀完成。
冒泡排序是一種簡(jiǎn)單的排序算法,其基本思想是通過(guò)相鄰元素的比較和交換來(lái)實(shí)現(xiàn)排序。
以下是使用 Java 實(shí)現(xiàn)冒泡排序的代碼示例:
public class BubbleSort {public static void bubbleSort(int[] arr) {int n = arr.length;
for (int i = 0; i < n - 1; i++) {for (int j = 0; j < n - i - 1; j++) {if (arr[j] > arr[j + 1]) {// 交換 arr[j] 和 arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
public static void main(String[] args) {int[] arr = {64, 34, 25, 12, 22, 11, 90};
bubbleSort(arr);
System.out.println(" 排序后的數(shù)組:");
for (int num : arr) {System.out.print(num + " ");
}
}
}
在上述代碼中,我們首先定義了一個(gè) bubbleSort
方法來(lái)實(shí)現(xiàn)冒泡排序。在每一輪循環(huán)中,我們通過(guò)比較相鄰元素的大小來(lái)決定是否交換它們的位置,將較大的元素逐漸“冒泡”到數(shù)組的末尾。最終,數(shù)組中的元素按照升序排列。
在 main
方法中,我們創(chuàng)建了一個(gè)整數(shù)數(shù)組,并調(diào)用 bubbleSort
方法來(lái)對(duì)其進(jìn)行排序。最后,我們輸出排序后的數(shù)組。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完