2.插入排序

2.插入排序

源代码:

#include <bits/stdc++.h>
using namespace std;
int main()
{
	int a[5]={5,6,1,2,3};
	for(int i=1;i<5;i++)   //n-1次排序   默认第一位是有序 故排序第一位后面得
	{
		int temp=a[i],j=i;  //记录a【i】 从j→i开始枚举
		while(j&&temp<a[j-1])  //如果temp<前一个元素
		{
			a[j]=a[j-1];  //将a【j-1】后移至a【j】
			j--;	
		}	
		a[j]=temp;  //插入未知是j
	} 
	for(int i=0 ;i<5;i++) cout<<a[i];
	return 0;
}


运行结果:

Process exited after 0.3157 seconds with return value 0
12356
--------------------------------
Process exited after 0.3157 seconds with return value 0
发布了3 篇原创文章 · 获赞 3 · 访问量 31

猜你喜欢

转载自blog.csdn.net/xg987599519/article/details/103947721
今日推荐