Java 冒泡排序算法实现详解 | 代码示例与原理分析
以下是使用 Java 编写的冒泡排序算法:
public class BubbleSort {
public static void main(String[] args) {
int[] array = {64, 34, 25, 12, 22, 11, 90};
System.out.println("排序前的数组:");
printArray(array);
bubbleSort(array);
System.out.println("排序后的数组:");
printArray(array);
}
public static void bubbleSort(int[] array) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (array[j] > array[j + 1]) {
// 交换array[j]和array[j+1]的位置
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
}
}
这是一个简单的冒泡排序算法示例,通过调用bubbleSort方法对数组进行排序,然后调用printArray方法打印结果。在冒泡排序算法中,通过比较相邻的元素,将较大的元素逐步交换到右边,最后得到一个有序的数组。
原文地址: https://www.cveoy.top/t/topic/qzDt 著作权归作者所有。请勿转载和采集!