Java 冒泡排序算法实现 - 代码示例和解释
以下是一个使用 Java 实现的冒泡排序算法示例代码:
public class BubbleSort {
public static void main(String[] args) {
int[] arr = { 5, 2, 8, 3, 1, 9, 4, 6, 7 };
System.out.println('Original array: ' + Arrays.toString(arr));
bubbleSort(arr);
System.out.println('Sorted array: ' + Arrays.toString(arr));
}
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]) {
// Swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
在上面的代码中,我们使用了冒泡排序算法对一个整型数组进行排序。在 bubbleSort 方法中,我们使用了两个嵌套的循环来比较相邻的元素,如果它们的顺序不对则交换它们的位置。通过不断重复这个过程,最终整个数组就会被排序好了。
原文地址: https://www.cveoy.top/t/topic/mRc6 著作权归作者所有。请勿转载和采集!