java做一个冒泡程序
时间: 2024-05-01 19:16:36 浏览: 12
以下是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 - 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] + " ");
}
}
}
```
这个程序使用了嵌套的循环来比较和交换相邻的元素,以便将最大的元素向右移动。外层循环执行n-1次,每次循环将当前最大的元素移动到数组的最右边。内层循环执行n-1-i次,每次循环比较相邻的元素并交换它们。最后,打印排序后的数组。
相关问题
用java写一个冒泡程序
下面是一个使用Java编写的冒泡排序程序,可以对整数数组进行排序:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 3, 8, 6, 4};
System.out.println("排序前的数组为:");
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
// 冒泡排序
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]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
System.out.println("排序后的数组为:");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
```
程序运行结果如下:
```
排序前的数组为:
5 3 8 6 4
排序后的数组为:
3 4 5 6 8
```
用Java写一个冒泡程序
以下是用Java写的冒泡程序示例:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 3, 8, 4, 2};
bubbleSort(arr);
for (int i : arr) {
System.out.print(i + " ");
}
}
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;
}
}
}
}
}
```
运行结果为:
```
2 3 4 5 8
```
该程序使用了双重循环来实现冒泡排序,外层循环控制排序轮数,内层循环控制比较次数。在每一轮比较中,如果前一个数大于后一个数,就交换它们的位置,直到最后一个数为止。最终输出排序后的数组。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)