数据结构 插入排序

来源:互联网 发布:知乎用户政治倾向 编辑:程序博客网 时间:2024/06/14 08:40
#include<iostream>//引入输入输出流 #include<stdlib.h>//使用库函数srand和rand #include<time.h>//使用库函数timeusing namespace std;const int Max=10;void Creat(int r[],int n);//定义数组函数void InsertSort(int r[],int n);int main(){int a[Max+1]={0},b[Max+1]={0};//定义一个可容纳Max+1个元素的整数型数组a和b,并将数组里的所有元素赋值为0int i=0;Creat(a,Max);//创建数组for(i=1;i<=Max;i++)//将数组a复制一份到数组bb[i]=a[i];cout<<"对于无序序列:";for(i=1;i<Max;i++)cout<<b[i]<<" ";cout<<endl;InsertSort(b,Max);//对数组进行排序cout<<"执行直接插入排序后,元素为:";for(i=1;i<=Max;i++)//打印数组cout<<b[i]<<" ";cout<<endl;return 0; }
void Creat(int r[],int n)//引用数组函数{int i=0;srand(time(NULL));for(i=1;i<=n;i++)r[i]=1+rand()%100;//待排序记录为二位数 }void InsertSort(int r[],int n)//0号单元用作暂存单元与监视哨 {int i,j;for( i=2;i<=n;i++){r[0]=r[i];for( j=i-1;r[0]<r[j];j--)r[j+1]=r[j];//记录后移 r[j+1]=r[0];}}  

原创粉丝点击