[Illustration] Java implements insertion sort (detailed comments)

1 Overview

   What is insertion sort?

Idea: The first element in the sequence is regarded as ordered, and each element after the sequence is compared, and then inserted into the numbered sequence until all the elements in the sequence are inserted.

Animation presentation:

2. Algorithm analysis

1. Starting from the first element, the element can be considered to have been sorted.
2. Take out the next element and scan from back to front in the sorted sequence of elements.
3. If the element (sorted) is larger than the new element, move the element to the next position.
4. Repeat step 3 until you find the position where the sorted element is less than or greater than the new element.
5. Insert the new element into this position.
6. Repeat step 2.

important point:

   ① Iterate from the second element, the for loop condition is i = 1

   ② Use j = i to record the position of the current inserted element to facilitate comparison of the previous elements

3. Code implementation

import java.util.Arrays;

public class InsertSort {
	
	public static void main(String[] args) {
		int[] array = {20,15,13,17,8,56,34,3};
		insertSort(array);
		for(int a = 0;a < array.length;a++) {
			System.out.println("排好序的数组为" + Arrays.toString(array));
		}
	}
	
	private static void insertSort(int[] array) {
		// 对数组进行遍历 默认数组的第一个元素是有序的 后面的元素依次和前一个元素比较
		for(int i = 1;i < array.length; i++) {
			// 取出来要和数组前面比较的元素
			int temp = array[i];
			// 记录下当前需要比较元素的位置 因为是和前面元素比较的 所以用 j 记录下
			// 使用 j 下标比较前面的元素就可以了
			int j = i;
			// 下标j > 0  说明第一个元素忽略;当前元素小于 前面的元素
			while(j > 0 && temp < array[j - 1]) {
				// 条件满足  则将前面的元素后移动一个位置
				array[j] = array[j - 1];
				// 继续往前面比较
				j--;
			}
			// 循环结束  说明需要插入的元素大于前面第一个元素了
			// 就把插入的元素赋值到所在位置
			// 因为j--, j 变化了  所以下标为j
			array[j] = temp;
		}
	}
}

4. Algorithm complexity analysis

If the goal is to arrange the sequence of n elements in ascending order, the best case and worst case for insertion sort are as follows.
Best case : The sequence is already arranged in ascending order. In this case, the comparison operations that need to be performed need (n-1) times.
Worst case : the sequence is in descending order, then there are n(n-1)/2 comparisons that need to be performed at this time.
Direct insertion sort is a stable sort. The worst time complexity is O(n^2), the best time complexity is O(n), and the space complexity is O(1).
The assignment operation of insertion sort is the number of comparison operations plus (n-1) times.
Therefore, insertion sort is not suitable for sorting applications with a relatively large amount of data.

Guess you like

Origin blog.csdn.net/Sunshineoe/article/details/114819634