用java冒泡排序 9 8 3 5 2
时间: 2023-04-06 09:01:34 浏览: 73
可以使用以下代码实现:
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]) {
// 交换 arr[j] 和 arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int[] arr = {9, 8, 3, 5, 2};
bubbleSort(arr);
System.out.println(Arrays.toString(arr)); // 输出 [2, 3, 5, 8, 9]
相关问题
Java 3 5 4 9生成一个冒泡排序
可以使用以下代码实现冒泡排序:
```
#include <stdio.h>
void bubbleSort(int arr[], int n) {
int i, j, temp;
for (i = ; i < n - 1; i++) {
for (j = ; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int arr[] = {3, 5, 4, 9};
int n = sizeof(arr) / sizeof(arr[]);
bubbleSort(arr, n);
printf("排序后的数组:\n");
for (int i = ; i < n; i++) {
printf("%d ", arr[i]);
}
return ;
}
```
冒泡排序java冒泡排序
冒泡排序是一种简单的排序算法,它重复地遍历要排序的列表,比较相邻的两个元素,并按照大小顺序交换它们,直到整个列表排序完成。下面是Java实现冒泡排序的代码示例:
```java
public class BubbleSort {
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]) {
// 交换arr[j]和arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};
bubbleSort(arr);
System.out.println("排序后的数组:");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
```
以上代码中,`bubbleSort`方法接收一个整型数组作为参数,并使用嵌套的循环来进行排序。外层循环控制需要比较的轮数,内层循环用于比较相邻元素并进行交换。最终得到的排序结果会打印在控制台上。
相关推荐
![](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)