用java写一个冒泡序列
时间: 2023-03-15 21:41:35 浏览: 63
```java
// 冒泡排序算法
public static void bubbleSort(int[] arr) {
int temp;
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]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
// 示例
int[] arr = {3, 9, 4, 7, 5, 0, 1, 6, 8, 2};
bubbleSort(arr);
for (int i : arr) {
System.out.print(i + " ");
}
```
上面的代码是一个简单的冒泡排序算法的实现,它将一个整型数组按升序排序。
相关问题
用Java写一个冒泡排序
好的,我来为您介绍如何用Java编写冒泡排序算法。
冒泡排序是一种简单的排序算法,其基本思想是将相邻的元素进行比较,如果前面的元素大于后面的元素,则交换这两个元素的位置,不断地进行比较和交换,直到整个序列有序为止。
下面是用Java编写冒泡排序算法的代码示例:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] arr = { 5, 2, 8, 3, 1, 6 };
bubbleSort(arr);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
public static void bubbleSort(int[] arr) {
int len = arr.length;
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < len - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
```
在这个示例中,我们定义了一个 `bubbleSort` 方法来实现冒泡排序,然后在 `main` 方法中调用这个方法对一个整数数组进行排序,并输出排序后的结果。具体实现过程是使用两个循环嵌套来比较和交换相邻的元素,直到整个序列有序为止。
希望这个代码示例对您有所帮助!
用java写一个冒泡排序
好的,这是Java实现冒泡排序的示例代码:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {3, 9, 1, 4, 6, 8, 2, 5, 7};
bubbleSort(arr);
System.out.println(Arrays.toString(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;
}
}
}
}
}
```
运行结果:
```
[1, 2, 3, 4, 5, 6, 7, 8, 9]
```
冒泡排序的核心思想是比较相邻的两个元素,如果前者比后者大,则交换它们的位置,这样一趟下来,最大的元素就会被交换到最后一个位置;然后再对前面的元素重复进行相同的操作,直到整个序列有序为止。
相关推荐
![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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)