写一个冒泡排序Java版女
时间: 2023-12-31 07:49:13 浏览: 23
好的,以下是Java版的冒泡排序代码:
```java
public static void bubbleSort(int[] array) {
int len = array.length;
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < len - 1 - i; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
```
其中,`array`是待排序的数组,`len`是数组的长度。外层循环控制排序的次数,内层循环控制每次排序的比较次数。如果前一个元素比后一个元素大,则交换它们的位置。经过多次排序,最终得到有序的数组。
相关问题
帮我写一个冒泡排序Java版
好的,以下是冒泡排序的Java代码实现:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 3, 9, 1};
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 - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
```
在上面的代码中,我们定义了一个bubbleSort方法来实现冒泡排序。该方法接收一个整型数组作为参数,然后对这个数组进行排序。在方法中,我们使用了两个for循环来进行排序,第一个循环控制排序的轮数,第二个循环控制每一轮中的比较和交换操作。在每一轮中,我们比较相邻的两个元素,如果前面的元素比后面的元素大,则交换它们的位置。最终,当所有轮数都完成后,我们就得到了一个有序的数组。
在上面的代码中,我们将排序后的数组输出到控制台上,你可以根据需要对输出进行修改。
写一个冒泡排序java
好的,以下是冒泡排序的JAVA代码:
```java
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;
}
}
}
}
```
该代码接受一个整数数组作为参数,并对数组进行冒泡排序。在冒泡排序中,我们通过比较相邻的元素并交换它们的位置来排序数组。时间复杂度为O(n^2)。
相关推荐
![](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)
![java](https://img-home.csdnimg.cn/images/20210720083646.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)