版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39993896/article/details/82805855
基本思想:
每步将一个待排序的几率按其顺序码大小插入到前面已排序的序列的合适位置(从后向前找到合适位置后),直到全部插入排序。
示例:
57,68,59,52
第一步: 57,68,59,52 (68>57,不处理)
第二步:57,68,59,52(57<59<68,插在57后)
第三步:57,59,68,52(52<57,插在57前)
结果:52,57,59,68
c++直接插入排序代码:
#include<iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;
int main() {
srand((unsigned) time(0));
int *a=new int[10];
for(int i=0; i<10; i++) {
a[i]=rand()%10;
cout<<a[i]<<" ";
}
cout<<endl;
for(int i=1; i<10; i++) {
int temp=a[i];
int k;
for(k=i-1;k>0;k--) {
if(temp>a[k]) {
a[k+1]=a[k];
} else
break;
}
a[k+1]=temp;
}
for(int i=0; i<10; i++) {
cout<<a[i]<<" ";
}
cout<<endl;
delete a;
return 0;
}
,