插入排序的九种算法

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值