1. public class 插入排序 {
    2. public static void main(String[] args) {
    3. int[] ints = {155, 55, 44, 56, 76, 13, 18, 55};
    4. int[] ints1 = insertionSort(ints);
    5. System.out.println(Arrays.toString(ints1));
    6. }
    7. public static int[] insertionSort(int[] arr) {
    8. // 非空判断
    9. if (arr.length == 0) {
    10. System.out.println("数组不能为空");
    11. return arr;
    12. }
    13. // 定义两个指针
    14. int current, pre;
    15. for (int i = 0; i < arr.length - 1; i++) {
    16. // current当前值
    17. current = arr[i + 1];
    18. // pre指向被比的值
    19. pre = i;
    20. // 循环判断current是否比左边的值小,小的话进行位置交换
    21. while (pre >= 0 && current < arr[pre]) {
    22. // 进行位置交换,为什么不用i呢,避免指针污染
    23. arr[pre + 1] = arr[pre];
    24. // pre-1,指向左边下一个要比的值
    25. pre--;
    26. }
    27. // pre!=i,说明发生了位置变换
    28. if (pre != i) {
    29. arr[pre + 1] = current;
    30. }
    31. }
    32. return arr;
    33. }
    34. }