帮我用Java写段 冒泡排序算法 1 2 6 9 4 2 3 6 9
时间: 2023-03-14 07:29:49 浏览: 73
我可以为你提供一个可行的Java冒泡排序算法:
public class BubbleSort {
public static void main(String[] args) {
int[] array = {1, 2, 6, 9, 4, 2, 3, 6, 9};
int temp = 0;
for(int i = 0; i < array.length-1; i++) {
for(int j = 0; j < array.length-1-i; j++) {
if(array[j] > array[j+1]) {
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
for(int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
}
相关问题
帮我写一段java冒泡排序算法
好的,以下是一段Java冒泡排序算法的代码:
```
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;
}
}
}
}
```
这段代码可以对一个整型数组进行冒泡排序,将数组中的元素按照从小到大的顺序排列。
帮我用Java语言写一个冒泡排序算法
以下是Java语言实现冒泡排序的代码:
```
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 3, 8, 4, 2};
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;
}
}
}
}
}
```
该代码定义了一个BubbleSort类,其中包含一个main方法和一个bubbleSort方法。在main方法中,先定义一个整型数组arr,并调用bubbleSort方法对该数组进行冒泡排序,最后输出排序结果。
bubbleSort方法接收一个整型数组作为参数,并使用两个循环对其进行排序。外层循环控制排序的轮数,内层循环控制每轮排序中相邻元素的比较和交换。如果前一个元素大于后一个元素,则交换它们的位置。最终,整个数组都会按照从小到大的顺序排列。
以上就是Java语言实现冒泡排序算法的代码,希望能够帮助到您。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)