Sorting algorithm - direct insertion sort

1.What is insertion sort

Direct insertion sort is a simple insertion sort method. Its basic idea is to insert the records to be sorted into an already sorted sequence one by one according to the size of their key values ​​until all records are inserted. , get a new ordered sequence. In practice, when we play poker, we use the idea of ​​​​insertion sorting.

Insert image description here

2. What is the use of insertion sort?

Insertion sort has several uses:

For sorting a small number of elements, it is an efficient algorithm
. For arrays that are already nearly sorted, it is very efficient, with a time complexity of O (N)
. It can be used as part of other complex sorting algorithms, such as quick sort
The essence of insertion

3. Implementation of insertion algorithm

When inserting the i (i>=1) element, the previous array[0], array[1],...,array[i-1] have been sorted. At this time, use the sorting code of array[i] and Compare the sorting code order of array[i-1], array[i-2],..., find the insertion position, insert array[i], and move the elements at the original position backward.

Insert image description here

Specific code implementation


//直接插入排序
void InsertSort(int* a, int n)//a是数组首元素地址,n是数组元素个数
{
    
    
	//[0-end]有序,end+1位置插进去,让[0-end+1]也有序
	int i = 0;
	int end = 0;
	for (i = 0; i < n - 1; i++)//对n个数进行排序,一共需要排n-1次
	{
    
    
		end = i;//下标标志end随着i的变化而变化
		int tmp = a[end + 1];//用tmp保存end+1位置的值,防止后面交换时丢失
		while (end >= 0)
		{
    
    
			if (a[end] > tmp)
			{
    
    
				a[end + 1] = a[end];//把a[end]赋给a[end+1](把较大值赋给较小值)(让较大值代替较小值)
				end--;//下标标志end-1;进行下一次循环,继续比较前两个数的值(a[end]和a[end+1]),
				      //直到end == -1,不再进入循环
			}
			else//如果tmp大于a[end],则跳出循环,执行下一个for循环
			{
    
    
				break;
			}
		}
		a[end + 1] = tmp;//循环完之后,将--后的end再+1的位置换成tmp,就实现了(end+1位置插进去,让[0-end+1]也有序)
		                 //如果循环完之后end没有--,则end+1位置还是tmp
	}
	//两个循环结束后,就排好了
}


4. Summary

  1. The closer the element set is to order, the more time-efficient the direct insertion sort algorithm is.

  2. Time complexity: O(N^2)

  3. Space complexity: O(1), it is a stable sorting algorithm

  4. Stability: stable

Guess you like

Origin blog.csdn.net/originalHSL/article/details/131238274