Insertion Sort [InsertionSort]

Insertion sort

Insertion sort works like sorting a hand of playing cards. Let's say the left hand is sorted and the unknown card on the table is
1. We start with an empty left hand and the cards on the table face down.
2. We then remove one card from the table at a time and insert it into the correct position in the left hand. In order to find the correct position to insert, we compare the card to be inserted with the card in the left hand, directly find the right position and insert it.

In the actual implementation process, we can regard the 0th element of the array as already sorted, and then start inserting from the second element.

Algorithm implementation

public class InsertionSort {

    public void insertionSort(int[] arr) {
        if(arr == null || arr.length < 2) {
            return ;
        }
        for (int i = 1; i < arr.length; i++) {
            for (int j = i; j > 0 && arr[j] < arr[j-1] ; j--) {
                swap(arr, j, j-1);
            }
        }
    }

    private void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp; 
    }
}

time complexity

Because each insertion needs to be compared, the time complexity isO(N^2)

stability

Because the inserted data is entered next to each other, the relative order before and after sorting will not change. So it is a stable algorithm.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325875472&siteId=291194637