1.直接插入排序
直接插入排序是插入排序算法中的一种,采用的方法是:在添加新的记录时,使用顺序查找的方式找到其要插入的位置,然后将新记录插入。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41 | #include<bits/stdc++.h>
using namespace std;
const int MAXN=1e4;
// 输出排序结果
void print(int a[],int i){
printf("%d:",i);
for(int j=1;j<=MAXN;j++)
printf("%d ",a[j]);
printf("\n");
}
// 直接插入排序函数
void InsertSort(int a[],int n){
for(int i=1;i<n;i++){
if(a[i]<a[i-1]){
//若第i个元素大于i-1元素则直接插入
int j=i-1;
int x=a[i];
while(j>-1&&x<a[j]){
a[j+1]=a[j];
j--;
}
a[j+1]=x;
}
//print(a,i);//打印每次排序结果
}
}
int a[MAXN+10];
int main(){
clock_t start,end;
start=clock();
for(int i=1;i<=MAXN;i++){
srand(i);
a[i]=rand();
}
InsertSort(a,MAXN);
print(a,MAXN);
end=clock();
cout<<"Time :"<<(double)(end-start)/CLOCKS_PER_SEC<<endl; //排序时间
return 0;
} |
2.折半插入
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39 | #include <stdio.h>
void print(int a[], int n ,int i){
printf("%d:",i);
for(int j=0; j<8; j++){
printf("%d",a[j]);
}
printf("\n");
}
void BInsertSort(int a[],int size){
int i,j,low = 0,high = 0,mid;
int temp = 0;
for (i=1; i<size; i++) {
low=0;
high=i-1;
temp=a[i];
//采用折半查找法判断插入位置,最终变量 low 表示插入位置
while (low<=high) {
mid=(low+high)/2;
if (a[mid]>temp) {
high=mid-1;
}else{
low=mid+1;
}
}
//有序表中插入位置后的元素统一后移
for (j=i; j>low; j--) {
a[j]=a[j-1];
}
a[low]=temp;//插入元素
print(a, 8, i);
}
}
int main(){
int a[8] = {3,1,7,5,2,4,9,6};
BInsertSort(a, 8);
return 0;
} |