插入排序之直接插入排序

#Innolight

基本思想

每步将一个待排序的记录,按其顺序码大小插入到前面已经排序的子序列的合适位置(从后向前找到合适位置后),直到全部插入排序完为止。

详细讲解

Pasted image 20250926155130.png

public class DirectInsertion {

    // 直接插入排序
    public int[] directInsertion(int[] nums) {
       int i, j, temp;
       for (i = 1; i < nums.length; ++i)
       {
            temp = nums[i];
            for (j = i - 1; j >= 0 && nums[j] > temp; --j) {
                nums[j + 1] = nums[j];
            }
            nums[j + 1] = temp;
       }
       return nums;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{57, 68, 59, 52};
        DirectInsertion d = new DirectInsertion();
        d.directInsertion(nums);
        for (int i = 0; i < nums.length; ++i) {
            System.out.println(nums[i]);
        }
    }

}
Note

直接插入排序是稳定排序