
- /**
- * 插入排序
- *
- * @version 1.0
- * @date 2023/09/01 18:48:44
- */
- public class Insert {
-
- /**
- * 升序插入排序
- *
- * @param a 待排序的数组
- * @date 2023/9/1 15:29:10
- */
- public static void sortAes(int[] a) {
- int length = a.length;
- for (int i = 1; i < length; i++) {
- for (int j = i; j > 0; j--) {
- //如果后一个数据大前一个数据
- if (a[j-1] > a[j]) {
- //交换数据
- int temp = a[j];
- a[j] = a[j-1];
- a[j-1] = temp;
- } else {
- break;
- }
- }
- }
- }
-
- /**
- * 降序插入排序
- *
- * @param a 待排序的数组
- * @date 2023/9/1 15:29:10
- */
- public static void sortDesc(int[] a) {
- int length = a.length;
- for (int i = 1; i < length; i++) {
- for (int j = i; j > 0; j--) {
- //如果后一个数据大前一个数据
- if (a[j-1] < a[j]) {
- //交换数据
- int temp = a[j];
- a[j] = a[j-1];
- a[j-1] = temp;
- } else {
- break;
- }
- }
- }
- }
- }
- public class InsertTest {
- public static void main(String[] args) {
- int[] array = {56, 88, 23, 99, 12, 34, -15, -15, -45, 78, 67, 32};
- //升序排列
- //Insert.sortAes(array);
- //降序排列
- Insert.sortDesc(array);
- System.out.println(Arrays.toString(array));
- }
- }