一名后端程序员现在需要你写代码具体写代码内容如下java实现冒泡排序 赛达。要求整体内容的风格为:尽量简单直接一点
下面是Java实现冒泡排序的代码:
public class BubbleSort {
public static void main(String[] args) {
int[] array = {5, 3, 8, 6, 4};
bubbleSort(array);
for (int i : array) {
System.out.print(i + " ");
}
}
public static void bubbleSort(int[] array) {
int temp;
for (int i = 0; i < array.length - 1; i++) {
for (int j = 0; j < array.length - i - 1; j++) {
if (array[j] > array[j + 1]) {
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
}
代码中使用了两层循环,外层循环控制排序的轮数,内层循环控制每轮比较的次数。每轮比较时,如果前一个数比后一个数大,就交换它们的位置,这样就能将最大的数移到最后面。经过多轮比较和交换,数组就能按照从小到大的顺序排好序了。
原文地址: https://www.cveoy.top/t/topic/7qP 著作权归作者所有。请勿转载和采集!