Java编写一个冒泡排序
时间: 2023-06-28 09:07:18 浏览: 47
以下是Java编写的冒泡排序代码:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 3, 1, 6};
bubbleSort(arr);
for (int i : arr) {
System.out.print(i + " ");
}
}
public static void bubbleSort(int[] arr) {
int len = arr.length;
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < len - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
```
以上代码中,我们定义了一个`bubbleSort`方法,该方法使用了双重循环实现冒泡排序算法。在`main`方法中,我们定义了一个待排序的整型数组,并调用`bubbleSort`方法进行排序。最后,我们遍历排序后的数组并将其输出。