Java 冒泡排序算法实现及代码示例 - 详细解析
冒泡排序是一种简单的排序算法,它重复地遍历要排序的列表,比较每对相邻的元素,并按照顺序交换它们,直到没有再需要交换的元素为止。下面是一个用Java实现的冒泡排序算法:
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("排序后的数组:");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
运行结果:
排序后的数组:
11 12 22 25 34 64 90
这段代码定义了一个BubbleSort类,其中的bubbleSort方法实现了冒泡排序算法。在main方法中,创建一个待排序的数组arr,然后调用bubbleSort方法对数组进行排序,并打印排序后的结果。
原文地址: https://www.cveoy.top/t/topic/qpNP 著作权归作者所有。请勿转载和采集!