写一个java的冒泡麦序
时间: 2024-04-29 09:23:59 浏览: 10
以下是一个Java的冒泡排序算法:
```
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 3, 9, 1};
bubbleSort(arr);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
public static void bubbleSort(int[] arr) {
int temp;
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]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
```
运行结果:
```
1 2 3 5 8 9
```
相关问题
写一个java冒泡麦序
以下是一个Java冒泡排序算法的示例:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 3, 8, 4, 2};
bubbleSort(arr);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
public static void bubbleSort(int[] arr) {
int temp;
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]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
```
在这个示例中,我们首先定义了一个名为`BubbleSort`的类,其中包含一个名为`main`的方法。`main`方法中声明了一个整数数组`arr`,并使用以下值进行初始化:5、3、8、4和2。然后调用`bubbleSort`方法对数组进行排序,并使用一个循环遍历数组并打印排序后的结果。
`bubbleSort`方法使用嵌套循环来执行冒泡排序。外部循环从数组的第一个元素开始,直到倒数第二个元素为止。内部循环从数组的第一个元素开始,直到当前外部循环的位置为止。在内部循环中,我们比较相邻的两个元素,如果前面的元素比后面的元素大,则交换它们的位置。这样,在每次内部循环结束时,我们都将数组中最大的元素移到了最后。当外部循环结束时,我们就完成了整个排序过程。
手写一个Java冒泡排序
手写一个Java冒泡排序算法非常直接,这是一个基本的排序算法,通过不断交换相邻元素,将较大的元素逐步“冒”到数组的末尾。以下是手写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 - 1 - i; j++) { // 内层循环用于比较并交换相邻元素
if (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[] numbers = {64, 34, 25, 12, 22, 11, 90};
bubbleSort(numbers);
System.out.println("Sorted array: ");
for (int num : numbers) {
System.out.print(num + " ");
}
}
}
```
相关推荐
![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)
![](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)
![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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)