1.冒泡排序思路分析图
2.根据图示先简单的实现每一轮的循环比较
public class BubbleSort {
public static void main(String[] args) {
int[] arr = new int[]{24, 69, 80, 57, 13};
for (int j = 0; j < 4; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
System.out.println("===第一轮===");
for (int j = 0; j < arr.length; j++) {
System.out.print(arr[j] + "\t");
}
for (int j = 0; j < 3; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
System.out.println("\n===第二轮===");
for (int j = 0; j < arr.length; j++) {
System.out.print(arr[j] + "\t");
}
for (int j = 0; j < 3; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
System.out.println("\n===第三轮===");
for (int j = 0; j < arr.length; j++) {
System.out.print(arr[j] + "\t");
}
for (int j = 0; j < 3; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
System.out.println("\n===第四轮===");
for (int j = 0; j < arr.length; j++) {
System.out.print(arr[j] + "\t");
}
}
}
3.最终实现代码
@Test
public void testBubbleSort() {
int[] arr = new int[]{24, 69, 80, 57, 13};
int temp;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
System.out.println("\n===第" + (i + 1) + "轮===");
for (int j = 0; j < arr.length; j++) {
System.out.print(arr[j] + "\t");
}
}
}