代码
package suanFa;
import java.util.Arrays;
public class MaoPap {
/**
* 冒泡排序
*
* @param arr 数组(乱序)
* @return
*/
public static int[] bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) { //0 1 2 3,四趟
for (int j = 0; j < n - i - 1; j++) { //i=0时,比较4次;i=1时,比较3次.....i=3时,比较1次
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
System.out.println(Arrays.toString(arr));
}
return arr;
}
public static void main(String[] args) {
int[] arr = {35, 12, 99, 18, 76};
System.out.println("排序中:");
int[] bubbleSort = bubbleSort(arr);
System.out.println("排序后:");
System.out.println(Arrays.toString(bubbleSort));
}
}
运行结果
排序中:
[12, 35, 18, 76, 99]
[12, 18, 35, 76, 99]
[12, 18, 35, 76, 99]
[12, 18, 35, 76, 99]
排序后:
[12, 18, 35, 76, 99]
博客展示了代码及其运行结果,聚焦信息技术领域代码相关内容。
1296

被折叠的 条评论
为什么被折叠?



