Detailed explanation of the top ten classic sorting algorithms (3): Insertion Sort

Algorithm principle

Each time an element is selected from the unordered part, inserted into the correct position in the ordered part, and this process is repeated until the entire array is sorted.

Algorithm Description

Insertion sort is a simple and intuitive sorting algorithm. Its basic idea is to insert an element to be sorted into an appropriate position in an already sorted sequence, thereby obtaining a new ordered sequence with a length plus one. The process of insertion sort is similar to the process of sorting playing cards.

Specific steps are as follows:

  1. Starting from the second element, treat it as the element to be sorted.
  2. The elements to be sorted are compared with the sorted sequence from right to left until a suitable position is found.
  3. Insert the elements to be sorted into the appropriate position so that the sequence after insertion is still in order.
  4. Repeat steps 2-3 until all elements have been inserted into the ordered sequence.

animation demonstration

Insert image description here

Code

  public static void insertionSort(int[] arr) {
    
    
        int n = arr.length;
        for (int i = 1; i < n; i++) {
    
    
            int key = arr[i];
            int j = i - 1;
            while (j >= 0 && arr[j] > key) {
    
    
                arr[j + 1] = arr[j];
                j--;
            }
            arr[j + 1] = key;
        }
    }

Algorithmic complexity

Time complexity (worst case) Time complexity (best) Time complexity (average) space complexity stability
O(n^2) O(n) O(n^2) O(1) Stablize

Optimization method of insertion sort:

  1. Binary search optimization: Use binary search in the sorted section to find the insertion position instead of comparing one by one. This reduces the number of comparisons.
  public static void binaryInsertionSort(int[] arr) {
    
    
        int n = arr.length;

        for (int i = 1; i < n; ++i) {
    
    
            int key = arr[i];
            //使用二分查找确定 key 的插入位置 j。这个位置是已排序部分中第一个大于 key 的元素的位置。
            int j = binarySearch(arr, 0, i - 1, key);

            // 移动已排序部分中大于key的元素
            // 比如原数组第一轮:3 1 5 8 2 7 -> 3 3 5 8 2 7,因为 3 > 1,所以把3 复制过去
            System.arraycopy(arr, j, arr, j + 1, i - j);

            // 在合适的位置插入key
            arr[j] = key;
        }
    }

    private static int binarySearch(int[] arr, int low, int high, int key) {
    
    
        while (low <= high) {
    
    
            int mid = low + (high - low) / 2;

            if (arr[mid] == key) {
    
    
                return mid;
            }

            if (arr[mid] < key) {
    
    
                low = mid + 1;
            } else {
    
    
                high = mid - 1;
            }
        }

        return low;
    }

Wuwuwu Erfen’s idea is really simple, but the devil is in the details.


Related concepts
稳定: If a is originally in front of b, and a=b, a will still be in front of b after sorting.
不稳定: If a is originally in front of b, and a=b, a may appear after b after sorting.
时间复杂度: The total number of operations on sorted data. Reflects the pattern of the number of operations when n changes.
空间复杂度: It refers to the measurement of the storage space required when the algorithm is executed in the computer. It is also a function of the data size n.

Guess you like

Origin blog.csdn.net/WriteBug001/article/details/134745105