写一个冒泡排序,java代码
时间: 2023-10-19 20:15:34 浏览: 40
以下是Java中的冒泡排序代码:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 3, 9, 1};
int temp;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = temp;
}
}
}
System.out.println(Arrays.toString(arr));
}
}
```
该代码使用了两个嵌套的循环来比较并交换相邻的元素,直到整个数组都被排序。第一个循环迭代数组中的每个元素,第二个循环迭代未排序的元素。如果相邻的元素顺序不正确,则交换它们。最后,打印已排序的数组。
相关问题
写一个冒泡排序的java代码
下面是一个简单的冒泡排序的Java代码:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 3, 1, 6, 9, 4, 7};
bubbleSort(arr);
for (int num : arr) {
System.out.print(num + " ");
}
}
public static void bubbleSort(int[] arr) {
int temp;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
```
这个代码中,我们使用了两层循环,外层循环控制排序的次数,内层循环用于比较相邻的两个元素,如果前面的元素比后面的元素大,则交换它们的位置。这样每次排序后,最大的元素就会沉到数组的最后面。通过多次排序,就可以将整个数组排序。
生成一个冒泡排序Java代码
当然可以,以下是一个简单的冒泡排序Java代码:
```
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 3, 1, 6};
int temp = 0;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
```
这是一个简单的冒泡排序代码,它可以对一个整数数组进行排序。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)