生成一段java代码实现冒泡排序
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 3, 8, 4, 2};
bubbleSort(arr);
System.out.println(Arrays.toString(arr));
}
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;
}
}
}
}
}
该程序先定义了一个数组,然后调用 bubbleSort 方法对数组进行排序,最后输出排序结果。bubbleSort 方法通过两个嵌套的循环来实现冒泡排序,外层循环控制比较的轮数,内层循环控制每轮比较的次数。如果前一个数比后一个数大,则交换两个数的位置。最终得到的数组就是从小到大排好序的。
原文地址: https://www.cveoy.top/t/topic/nGY 著作权归作者所有。请勿转载和采集!