用java写个冒泡排序
时间: 2023-02-23 19:02:43 浏览: 43
您好,冒泡排序是一种常见的排序算法,它可以通过比较相邻元素的大小来交换位置,从而达到排序的目的。下面是一个java实现的冒泡排序例子:
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 7, 3, 8, 1};
// 从小到大排序
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;
}
}
}
// 打印排序后的数组
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
相关问题
用JAVA写个冒泡排序
好的,以下是使用 Java 语言实现冒泡排序的代码:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};
System.out.println("排序前的数组:");
printArray(arr);
bubbleSort(arr);
System.out.println("\n排序后的数组:");
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] + " ");
}
}
}
```
运行结果:
```
排序前的数组:
64 34 25 12 22 11 90
排序后的数组:
11 12 22 25 34 64 90
```
以上代码中,`bubbleSort` 函数实现了冒泡排序算法,`printArray` 函数用于打印数组元素。在 `main` 函数中我们初始化了一个整数数组并对其进行排序,最后输出排序后的数组元素。
用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 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;
}
}
}
}
}
```
该代码使用了双重循环,外层循环控制比较轮数,内层循环控制每轮比较的次数。在每轮比较中,如果前一个元素比后一个元素大,则交换它们的位置,直到最后一轮比较完成。
相关推荐
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.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)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)