编写一个java的冒泡排序
时间: 2023-03-13 13:26:41 浏览: 64
好的,给你一个Java的冒泡排序程序:
public class BubbleSort {
//比较相邻的元素。如果第一个比第二个大,就交换他们两个。
public static void bubbleSort(int[] arr) {
int n = arr.length;
int temp;
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(arr[j-1] > arr[j]){
//swap elements
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
}
}
相关问题
编写一个java冒泡排序
以下是使用Java实现冒泡排序的示例代码:
```java
public class BubbleSort {
public static void main(String[] args) {
// 定义数组
int[] arr = {5, 3, 8, 6, 4};
// 冒泡排序
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] + " ");
}
}
}
```
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 len = arr.length;
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < len - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
```
以上代码中,我们定义了一个`bubbleSort`方法,该方法使用了双重循环实现冒泡排序算法。在`main`方法中,我们定义了一个待排序的整型数组,并调用`bubbleSort`方法进行排序。最后,我们遍历排序后的数组并将其输出。
相关推荐
![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)
![](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)
![](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)