【算法】插入排序法

一、介绍

1.插入排序是简单排序算法中的一种,它主要适用于包括向量和列表在内的任何序列结构

二、思路

1.将数列分为有序前缀和无序后缀两部分,将后缀首元素不断往前缀中移动,直至后缀无元素

2.存在一个标识位,标识有序前缀和无序后缀,即s[0,r)为有序前缀,s[r,n-1]为无序后缀

3.将元素s[r]往前插入时,需要注意元素的位置移动,此时是在s[0,r]区间进行插入,从后往前比较,若后者比前者小,则交换两者位置,直至到达首位

三、程序

1.程序

#include "stdafx.h"
#include<iostream>

using namespace std;

void InsertSort(int A[],int n)
{
	for(int r = 1; r < n; r++) //r为标识位,标识排序部分和未排序部分
	{
		for(int i = r - 1; i >= 0; i--)
		{
			if (A[i+1] < A[i]) //将一个元素插入前侧排序部分
			{
				int temp = A[i+1];
				A[i+1] = A[i];
				A[i] = temp;
			}
		}
	}
}

2.测试用例

void TestInsertSort()
{
	int A[] = {2,3,7,8,4,9,10,23,45,13,5,1};
	int n = 12;
	std ::cout << "排序前的数组:" ;
	for (int i = 0 ;i < n ; i++)
	{
		std ::cout << A[i]<<" " ;
	}
	InsertSort(A,n);
	std ::cout << "排序后的数组:" ;
	for (int i = 0 ;i < n ; i++)
	{
		std ::cout  << A[i]<<" " ;
	}
}

3.输出

四、复杂度

O(n^2)

猜你喜欢

转载自blog.csdn.net/shuwenting/article/details/81905416