用java 寫一個冒泡排序
时间: 2023-11-19 11:55:44 浏览: 14
以下是用Java写的冒泡排序的代码:
```
public class BubbleSort {
public static void sort(int array[]) {
//i表示第几轮“冒泡”,j 表示“走访”到的元素索引。
//每一轮“冒泡”中,j 需要从列表开头“走访”到 array.length - 1 的位置。
for (int i = 0; i < array.length - 1; i++) {
for (int j = 0; j < array.length - 1 - i; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
}
```
以上代码中,sort方法接收一个整型数组作为参数,对该数组进行冒泡排序。在每一轮“冒泡”中,从列表开头“走访”到数组末尾,比较相邻两个元素的大小,如果前一个元素大于后一个元素,则交换它们的位置。经过多轮“冒泡”后,数组中的元素就会按照从小到大的顺序排列。
相关问题
用java写一个冒泡排序
好的,以下是用 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 n = arr.length;
for (int i = ; i < n - 1; i++) {
for (int j = ; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int 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, 8, 4, 9};
// 冒泡排序
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;
}
}
}
// 输出排序后的结果
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
```
上面的代码中,我们定义了一个 `BubbleSort` 类,包含了一个 `main` 方法,用于执行冒泡排序的算法。我们首先定义一个整型数组 `arr`,并给其赋初值。然后,我们使用两个嵌套的 `for` 循环进行冒泡排序,最后输出排序后的结果。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)