插入排序法

来源:互联网 发布:涵曦网络传销窝点 编辑:程序博客网 时间:2024/04/29 03:01
#include <iostream>
#include 
<time.h>
using namespace std;
const int MAX=10;

void InsertSort(int a[]);//插入排序法声明
int main()
...{
    
int Number[MAX]=...{0};//初始化一个包含10个元素的零数组;
    srand(time(NULL));//随机种子
    for (int i=0;i<MAX;i++)
    
...{
        Number[i]
=rand()%100;//产生伪随机数
        cout<<Number[i]<<"";//输出这10个伪随机数
    }

    InsertSort(Number);
//插入排序;
    for (int j=0;j<MAX;j++)
    
...{
        cout
<<Number[j]<<"";//输出排序后的数组;
    }

    
return 0;
}

void InsertSort(int a[])//插入排序法定义
...{
    
int i,j,temp;//temp为哨兵,存放当前要插入的数
    
    
for (j=1;j<MAX;j++)//从第二个数据开始插入排序
    ...{
        temp
=a[j];//把当前要插入的数据放入哨兵中;
        i=j-1;//已经排序的数组下标
        while (temp<a[i])//当哨兵元素比已排序的元素小时
        ...{
            a[i
+1]=a[i];//已排序元素右移
            i--;
            
if (i==-1)//如果已排序元素下标为-1则退出
            ...{
                
break;
            }

        }

        a[i
+1]=temp;//把哨兵元素放入完成排序
    }

}