写一个冒泡程序java
时间: 2023-12-21 13:03:33 浏览: 24
这是一个用Java实现的冒泡排序程序的示例代码:
```
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};
bubbleSort(arr);
System.out.println("排序后的数组:");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
static void bubbleSort(int[] arr) {
int n = arr.length;
int temp;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
```
该程序实现了冒泡排序算法,它可以对数组进行排序,将数组中的数从小到大排序。
相关问题
java程序写一个冒泡程序
以下是一个简单的 Java 冒泡排序程序:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 2, 9, 4, 7};
System.out.println("排序前的数组为:");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
// 冒泡排序
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]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
System.out.println("\n排序后的数组为:");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
```
输出结果如下:
```
排序前的数组为:
5 2 9 4 7
排序后的数组为:
2 4 5 7 9
```
用java写一个冒泡程序
下面是一个用 Java 写的冒泡排序程序:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {3, 1, 6, 2, 9, 4, 7, 5, 8};
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;
}
}
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
```
这个程序使用了两个嵌套的 for 循环,外层循环控制排序的轮数,内层循环控制每轮中比较的次数。在每轮比较中,如果前一个数比后一个数大,就交换它们的位置。最终得到的数组就是排好序的。
相关推荐
![](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)
![text/x-java](https://img-home.csdnimg.cn/images/20210720083646.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)