diff --git a/s-day04/src/com/inmind/sort05/SortDemo12.java b/s-day04/src/com/inmind/sort05/SortDemo12.java new file mode 100644 index 0000000..7b97f8f --- /dev/null +++ b/s-day04/src/com/inmind/sort05/SortDemo12.java @@ -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)); + } +}