用java写一个冒泡程序
时间: 2023-11-01 17:07:59 浏览: 26
下面是一个简单的Java冒泡排序程序:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] array = {5, 1, 12, -5, 16, 2, 12, 14};
for (int i = 0; i < array.length - 1; i++) {
for (int j = 0; j < array.length - i - 1; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
System.out.println(Arrays.toString(array));
}
}
```
输出:
```
[-5, 1, 2, 5, 12, 12, 14, 16]
```
该程序使用了两个嵌套循环来实现冒泡排序。外层循环控制排序的轮数,内层循环控制每轮比较的次数。在每轮比较中,如果相邻的两个元素大小关系不正确,就交换它们的位置。最终得到的数组就是按升序排列的。
相关问题
用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
```
该程序使用了双重循环来实现冒泡排序,外层循环控制排序轮数,内层循环控制比较次数。在每一轮比较中,如果前一个数大于后一个数,就交换它们的位置,直到最后一个数为止。最终输出排序后的数组。
用JAVA写一个冒泡成程序
好的,这是用Java写的一个冒泡排序程序:
```
import java.util.Arrays;
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 4, 3, 2, 1};
bubbleSort(arr);
System.out.println(Arrays.toString(arr));
}
public static void bubbleSort(int[] arr) {
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;
}
}
}
}
}
```
输出结果:
```
[1, 2, 3, 4, 5]
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)