写一个java 冒泡排序
时间: 2023-09-16 14:05:36 浏览: 54
### 回答1:
以下是Java语言实现的冒泡排序算法:
```java
public class BubbleSort {
public static void sort(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 main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};
sort(arr);
System.out.println(Arrays.toString(arr));
}
}
```
该算法的时间复杂度为O(n^2),不适合处理大规模数据。
### 回答2:
冒泡排序(Bubble Sort)是一种简单且有效的排序算法,它重复地遍历待排序的元素,每次比较相邻的两个元素,并依次交换位置,直到整个序列有序。
下面是用Java语言编写的冒泡排序代码:
```java
public class BubbleSort {
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]) {
// 交换arr[j]和arr[j+1]的位置
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};
bubbleSort(arr);
System.out.println("排序后的数组:");
for (int i : arr) {
System.out.print(i + " ");
}
}
}
```
这个冒泡排序算法的时间复杂度为O(n^2),其中n为待排序元素的数量。在上述代码中,我们通过两个嵌套的for循环来遍历数组,并通过比较相邻元素的值来实现交换操作。插入排序会将待排序部分的最大值逐渐"冒泡"到末尾,因此称为冒泡排序。
以上代码仅是示例,你可以根据自己的需要进行修改和扩展。
### 回答3:
冒泡排序是一种简单的排序算法,它重复地遍历要排序的列表,比较相邻的元素,并按照大小顺序交换它们,直到整个列表排序完成。以下是Java实现的冒泡排序算法:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};
bubbleSort(arr);
System.out.println("排序后的数组:");
for (int num : arr) {
System.out.print(num + " ");
}
}
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]) {
// 交换arr[j]和arr[j+1]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
}
```
此代码首先定义了一个`bubbleSort`方法,接收一个整数数组作为参数,并使用两个嵌套的循环来遍历并比较数组中的元素。内部的循环将当前元素与下一个元素进行比较,如果当前元素大于下一个元素,则交换它们的位置。
然后,`main`方法创建一个示例整数数组,调用`bubbleSort`方法对其进行排序,并打印排序后的结果。最终输出的结果应为:11 12 22 25 34 64 90。
冒泡排序的时间复杂度为O(n^2),其中n是要排序的元素数量。虽然冒泡排序是一种简单的排序算法,但对于较大的数据集,其效率相对较低,通常不推荐在实际应用中使用。
相关推荐
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![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)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)