用Java语音写一个冒泡排序算法
时间: 2023-03-15 16:59:57 浏览: 64
public static void bubbleSort(int[] array) {
int n = array.length;
int temp = 0;
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(array[j-1] > array[j]){
//swap elements
temp = array[j-1];
array[j-1] = array[j];
array[j] = temp;
}
}
}
}
相关问题
用java语言写一个冒泡排序算法
好的,以下是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()`函数对其进行排序。函数中使用两个嵌套循环来比较相邻元素的大小,并交换它们的位置,从而逐步将最大的元素移动到数组的末尾。最终,数组中的元素就按照从小到大的顺序排列好了。
帮我用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_column_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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)