请用java写个冒泡排序
时间: 2023-08-31 16:40:36 浏览: 38
### 回答1:
好的,以下是Java语言实现的冒泡排序代码:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] nums = {5, 2, 8, 3, 1, 6};
bubbleSort(nums);
System.out.println(Arrays.toString(nums));
}
public static void bubbleSort(int[] nums) {
int len = nums.length;
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < len - i - 1; j++) {
if (nums[j] > nums[j + 1]) {
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
}
}
}
}
}
```
以上代码中,我们首先定义了一个 `bubbleSort` 方法,该方法接收一个整型数组作为参数,并使用冒泡排序算法对数组进行排序。排序过程中,我们使用了两个 for 循环来遍历数组并比较相邻元素的大小,如果前一个元素比后一个元素大,则交换它们的位置。通过多次遍历,我们可以将整个数组排序完成。最后,我们在 `main` 方法中调用 `bubbleSort` 方法对给定的数组进行排序,并使用 `Arrays.toString` 方法将排序后的数组输出到控制台。
### 回答2:
冒泡排序是一种简单的排序算法,它重复地遍历待排序的元素,比较相邻的两个元素,并按照规定的顺序交换位置,直到整个序列有序为止。
以下是使用Java语言实现冒泡排序的示例代码:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 3, 8, 4, 2};
bubbleSort(arr);
System.out.println("排序后的数组:");
printArray(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;
}
}
}
}
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
```
以上代码中的`bubbleSort`方法使用了两层嵌套循环来实现冒泡排序。外层循环控制比较的轮数,每一轮将最大的元素移到最右边;内层循环用于比较相邻元素并交换位置。`printArray`方法用于打印排序结果。运行以上代码,输出结果为`2 3 4 5 8`,表示排序后的数组。
相关推荐
![](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)
![mht](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)