插入排序算法

【实例描述】

  原理:对数组的前某个数量元素进行比较,将其最大元素置于最前,其实现过程如图:

  

【实现过程】

  定义函数InsertSort()实现直接插入排序算法,定义int型数组变量a作为目标排序数组,代码如下:

#include<iostream>
using namespace std;
#define M 11  //定义数组的大小
void InsertSort(int a[])
{
	cout<<"排序过程:"<<endl;
	int temp;
	int i,j;
	for(i=0;i<M;i++)//这个循环用来实现对其i个元素进行比较大小后的排序,直到对M-1个元素进行排序
	{
		temp=a[i];
		for(j=i;i>0&&a[j-1]>temp;j--)//如歌这两个条件不能同时满足,不能交换相邻元素值
			a[j]=a[j-1];
		a[j]=temp;//比较值只能赋给最后参与交换的a[j]元素
		for(int k=0;k<M;k++)
			cout<<a[k]<<" ";
		cout<<endl;
	}
}
void main()
{
	cout<<"-----------插入排序------------"<<endl;
	int a[M]={0,209,386,768,185,247,606,230,834,54,121};
	cout<<"排序之前的元素为:
";
	for(int i=0;i<M;i++)
		cout<<a[i]<<" ";
	cout<<endl;
	InsertSort(a);
	cout<<"排序结果为:
";
	for(i=0;i<M;i++)
		cout<<a[i]<<" ";
	cout<<endl;
}
原文地址:https://www.cnblogs.com/0405mxh/p/10129290.html