一、直接插入排序算法
1、基本思想:将一个记录插入到已经排好序的有序表中,从而得到一个新的、记录数增
1的有序表。
2、相应的代码实例如下:
#include<iostream>
#include <time.h>
using namespace std;
#define ARR_MAX 10 // 假设有10个数
//直接插入排序(升序)
void insert_sort(int a[],int n)
{
int i,j,temp;
for(i=1;i<n;i++)//需要选择n-1次
{
temp=a[i];//暂存下标为1的数,下标从1开始,因为开始时下标为0的数,前面没有任何数,此时认为它是排好顺序的
for(j=i-1;j>=0 && temp<a[j];j--)
{//如果满足条件就往后挪
a[j+1]=a[j];
}
a[j+1]=temp;//找到下标为i的数的放置位置
}
}
void print_arry(int a[], int len)
{
for(int i=0;i<len;i++)//循环打印数组的每个元素
{
cout<<a[i]<<" ";
}
cout<<endl;
}
int main()
{
srand((unsigned)time(NULL)); // 随机种子
int t[ARR_MAX];
cout<<"排序前:";
for (int i=0;i<ARR_MAX;i++)
{
t[i]=rand()%1000+1; // 随机数为1~1000
cout<<t[i]<<" ";
}
cout<<endl;
insert_sort(t,ARR_MAX);
cout<<"排序后:";
print_arry(t,ARR_MAX);
return 0;
}
3、运行效果如下: