用Java写个冒泡排序
时间: 2023-09-15 16:05:55 浏览: 69
### 回答1:
好的,这是用 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] + " ");
}
}
}
```
冒泡排序的原理是:每次比较相邻的两个元素,如果它们的顺序错误就交换位置,这样每一轮排序后都会将最大(或最小)的元素“浮”到数组的最后(或最前)。冒泡排序的时间复杂度为 O(n^2),因此在排序大数据时效率较低。
### 回答2:
冒泡排序是一种简单且常用的排序算法,下面是用Java语言实现冒泡排序的示例代码:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] array = {5, 2, 8, 3, 1};
bubbleSort(array);
System.out.println("排序后的数组:");
for (int num : array) {
System.out.print(num + " ");
}
}
public static void bubbleSort(int[] array) {
int n = array.length;
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (array[j] > array[j+1]) {
// 交换array[j]和array[j+1]的位置
int temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
}
}
```
以上代码中,首先定义了一个`bubbleSort`方法来实现冒泡排序。该方法接受一个整型数组作为参数,并通过两层嵌套的循环遍历数组进行排序。在内层循环中,比较相邻的两个元素,如果前一个元素比后一个元素大,则交换它们的位置。通过这样的比较和交换操作,每一轮都可以将当前未排序的最大元素移到正确的位置。外层循环控制了排序的轮数,每轮排序都可以确定一个最大的元素的位置。最后,打印排序后的数组。
使用上述示例代码,可以得到冒泡排序后的结果为:1 2 3 5 8。
### 回答3:
冒泡排序是一种简单但效率较低的排序算法。它通过重复地比较相邻的两个元素,并根据需要交换它们的位置,直到序列排序完成。
下面是用Java写的一个冒泡排序的示例:
```java
public class BubbleSort {
public static void bubbleSort(int[] array) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (array[j] > array[j + 1]) {
// 交换array[j]和array[j + 1]的位置
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
public static void main(String[] args) {
int[] array = {5, 2, 8, 12, 1, 6, 4}; // 待排序的数组
bubbleSort(array);
for (int num : array) {
System.out.print(num + " ");
}
}
}
```
以上代码实现了一个冒泡排序算法。`bubbleSort`方法接受一个整数数组作为参数,并对数组进行冒泡排序。`main`方法中创建了一个待排序的数组,并调用`bubbleSort`方法对数组进行排序。最后,打印排序后的数组元素。
冒泡排序的时间复杂度为O(n^2),其中n是待排序数组的长度。它是一种简单但效率较低的排序算法,适用于待排序数组较小的情况。
相关推荐
![](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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)