直接插入排序

#include <iostream>
using namespace std;
//直接插入排序,升序
void InserSort(int n[], int length)
{
	int i, j;
	for (i=1;i<length;i++)//从第2个元素开始插入,前面的为排好序的序列
	{
		int t=n[i];//待插入的数字
		j=i;
		while (n[j- 1]> t&& j> 0)//依次移动元素,j个元素
		{
			n[j]= n[j- 1];//如果元素大于t,则右移元素
			j--;
		}
		n[j]= t;//插入t

	}
}
int main()
{
	int t;
	cin>>t;
	int n[100000];
	int i=0;
	for (;i< t; i++)
	{
		cin>>n[i];
	}
	InserSort(n,t);
	cout<<"排序后:"<<endl;
	for (i= 0; i< t;i++)
	{		
		cout<<n[i];
		if(i< t- 1 ) cout<<' ';
	}
	
	cout<<endl;
}

  

原文地址:https://www.cnblogs.com/ibosong/p/2908268.html