-
Insertion sort
The principle of insertion sort is very simple. It is said that a set of data is divided into two groups, which I call the ordered group and the to-be-inserted group respectively. Each time an element is taken out of the group to be inserted, compared with the elements of the ordered group, and a suitable position is found, and the element is inserted into the ordered group. In this way, each time an element is inserted, the ordered group increases and the group to be inserted decreases. Until the number of elements in the group to be inserted is 0. Of course, the insertion process involves movement of elements.
Insertion sort time complexity
If the goal is to sort a sequence of n elements in ascending order, there are best and worst cases for using insertion sort. The best case is that the sequence is already in ascending order, in which case, the comparison operation needs to be performed (n-1) times. The worst case is that the sequence is sorted in descending order, then a total of n(n-1)/2 comparisons need to be performed at this time. The assignment operation of insertion sort is the number of comparison operations plus (n-1) times. On average, the time complexity of the insertion sort algorithm is O(n^2). Therefore, insertion sort is not suitable for sorting applications with a relatively large amount of data. However, if the amount of data that needs to be sorted is small, for example, on the order of less than a thousand, then insertion sort is still a good choice.
package sort; public class Insertion { public static void insertion(int[] arr){ for(int i=1;i<arr.length;i++){ int j = i-1; int temp = arr[i]; while(j>=0 && temp<arr[j]){ arr[j+1] = arr[j]; j--; } arr[j+1] = temp; } } public static void main(String[] args) { int[] arr = {6,2,4,8,5,7,1}; for (int i : arr) { System.out.print(i+" "); } System.out.println(); insertion(arr); for (int i : arr) { System.out.print(i+" "); } } }