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("/n排序后数组:");
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
类,其中 bubbleSort
方法实现了冒泡排序算法。在 main
方法中,我们创建一个整数数组,然后调用 bubbleSort
方法对其进行排序,并打印排序前后的数组。
评论内容