用java写一个冒泡排序
时间: 2023-09-21 22:05:50 浏览: 62
### 回答1:
好的,这是一个用 Java 写的冒泡排序的示例代码:
```
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 1, 4, 2, 8};
bubbleSort(arr);
for (int i : arr) {
System.out.print(i + " ");
}
}
public static void bubbleSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
```
算法的原理是:每一次比较相邻的两个数,如果它们的顺序错误就交换它们。重复这一过程直到没有任何一对数字需要交换,也就是说数列已经排序完成。
上面的代码中,我们使用了两层循环来实现冒泡排序。在第一层循环中,我们从数组的第一个数开始,遍历到数组的最后一个数。在第二层循环中,我们从数组的第一个数开始,遍历到数组的第 `arr.length - i - 1` 个数。我们在第二层循环中比较相邻的两个数,并交换它们的位置如果它们的顺序错误。
希望这对你有帮助。如果你有其他问题,请随时告诉我。
### 回答2:
冒泡排序是一种简单的排序算法,它重复地遍历待排序的元素,比较相邻的两个元素,并将顺序不符合要求的元素交换位置,直到整个序列有序为止。
下面是使用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};
System.out.println("排序前的数组:");
for (int num : arr) {
System.out.print(num + " ");
}
bubbleSort(arr);
System.out.println("\n排序后的数组:");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
```
该程序先输出未排序的数组,然后调用`bubbleSort`方法对数组进行排序,最后输出排序后的数组。
运行结果为:
```
排序前的数组:
64 34 25 12 22 11 90
排序后的数组:
11 12 22 25 34 64 90
```
这段代码使用了两层循环,外层循环控制需要多少轮比较,内层循环负责相邻元素的比较和交换。每一轮比较都会找出当前未排序元素中最大的数放到最后,因此经过多轮比较后,整个数组就会有序。
### 回答3:
冒泡排序是一种简单的排序算法,它重复地遍历要排序的数组,每次比较相邻的两个元素,如果顺序不对则交换它们,直到整个数组排序完成。
以下是使用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]) {
// 交换相邻两个元素
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 = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
```
这段代码首先定义了一个静态方法`bubbleSort()`,接受一个整数数组作为参数。这个方法通过两重循环遍历数组,比较相邻元素的大小,并进行交换。外层循环控制需要排序的次数,内层循环进行相邻元素的比较。
接下来,在`main()`方法中定义了一个整数数组`arr`并初始化,然后调用`bubbleSort()`方法对数组进行排序。最后,使用循环遍历数组并输出排序后的结果。
以上就是使用Java实现冒泡排序的代码和解释,希望能对你有所帮助。