s-day04-冒泡排序

This commit is contained in:
2026-08-03 13:56:03 +08:00
parent 6d8d7ef388
commit f0ec8dfee1
@@ -0,0 +1,27 @@
package com.inmind.sort05;
import java.util.Arrays;
/*
冒泡排序
*/
public class SortDemo12 {
public static void main(String[] args) {
//创建一个数组
int[] arr = {1, 5, 3, 4, 2};
//5个数字,要排4趟
for (int i = 0; i < arr.length - 1; i++) {//循环4次
//每趟排序的次数刚好就是arr.length - 1-i
for (int j = 0; j < arr.length - 1 - i; j++) {
//每趟中每次都是相邻比较,如果大或者小就往后(升序,降序)
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));
}
}