冒泡排序java实现的代码
时间: 2023-03-03 14:54:08 浏览: 60
public static void bubbleSort(int[] arr) {
int n = arr.length;
int temp = 0;
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 static void bubbleSort(int[] arr) {
int n = arr.length;
// 遍历所有数组元素
for (int i = 0; i < n; i++) {
// Last i elements are already sorted
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;
}
}
}
}
```
这里的 `arr` 是要排序的数组。这个函数是原地排序,也就是说,不需要额外的空间来存储排序后的数组。
冒泡排序Java所有实现代码
好的,以下是Java实现冒泡排序的代码:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {3, 1, 6, 2, 8, 4, 5, 9, 7};
bubbleSort(arr);
System.out.println(Arrays.toString(arr));
}
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;
}
}
}
}
}
```
冒泡排序的基本思想是:通过不断比较相邻的元素,将较大的元素交换到后面,从而实现整个序列的排序。这里的代码中,使用了两重循环,外层循环控制排序的轮数,内层循环控制每轮排序的次数。如果前一个元素比后一个元素大,则交换这两个元素的位置。最终,当所有的轮数都执行完毕后,数组中的元素就会按照从小到大的顺序排列好。
相关推荐
![](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)