以下是使用Java实现冒泡排序的代码:
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 9, 1};
bubbleSort(arr);
System.out.println("排序后的数组:");
for (int num : arr) {
System.out.print(num + " ");
}
}
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]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
}
在上面的代码中,我们定义了一个bubbleSort
方法来实现冒泡排序。它使用两层循环,外层循环控制遍历的轮数,内层循环用于比较相邻元素并交换位置。如果当前元素大于下一个元素,则交换它们的位置。
在main
方法中,我们定义了一个整数数组arr
并调用bubbleSort
方法来对其进行排序。最后,我们打印排序后的数组。