本文原创,转载请注明出处(羅小亮博客)。如果本文如果有雷同观点,纯属巧合。如果有引述他人成果,必会给出处。
核心思想:将一个记录直接插入到已经排好序的有序表中,从而得到一个新的、记录数增加1的有序表。
代码如下:
#include <iostream>
using namespace std;
void InsertSort(int a[],int n);
int main()
{
using namespace std;
void InsertSort(int a[],int n);
int main()
{
int a[10]={5,8,2,1,6,7,9,4,3,0};InsertSort(a,10);for(int i=0;i<10;++i)cout << a[i];cout << endl;system("pause");return 0;
}
void InsertSort(int a[],int n)
{
void InsertSort(int a[],int n)
{
int temp,i,j;for(i=1;i<n;++i){
if(a[i]<a[i-1]){
temp=a[i];for(j=i-1;(a[j]>temp)&&(j>=0);--j){a[j+1]=a[j];}a[j+1]=temp;
}
}
}
当找到一个值比前面那个值小,则把小的值放入temp中,然后将前面的值与temp比较,如果比temp大,则该值向后移。如果比temp小,则放在该值的后面