code show as below:
public class Main {
// 实例演示
public static void main(String[] args) {
int[] arr = {3, 5, 6, 2, 1};
arrPrint(arr);
BubbleSort(arr);
arrPrint(arr);
}
// 冒泡排序算法
// 第一级for循环,i从arr的尾端遍历到头。
// 第二级for循环,j则从头遍历至i。
// j的循环走完一次,i左移,j的遍历范围缩短一位。
private static void BubbleSort(int[] arr) {
int temp = 0;
for (int i = arr.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = temp;
}
}
}
}
// 打印函数
private static void arrPrint(int[] arr) {
StringBuilder str = new StringBuilder();
str.append("[");
for (int v : arr) {
str.append(v + ", ");
}
str.delete(str.length() - 2, str.length());
str.append("]");
System.out.println(str.toString());
}
}
Omit afterwards