1 package com.example.demo;
2
3 public class InsertSort {
4 public void insertSort(int[] arr) {
5 int i, j;
6 for (i = 0; i < arr.length; i++) {
7 int temp = arr[i];//temp为哨兵
8 for (j = i - 1; j >= 0 && arr[j] > temp; j--) {
9 arr[j + 1] = arr[j];//逐个向后移
10 }
11 arr[j + 1] = temp;//temp插入位置
12 }
13 for (int k : arr) {
14 System.out.print(k + " ");
15 }
16 }
17
18 public static void main(String args[]) {
19 int[] arr = { 12, 3, 4, 5, 6, 9, 1, 7 };
20 InsertSort sort = new InsertSort();
21 sort.insertSort(arr);
22 }
23
24 }