排序算法

@Adrian

一、插入排序
#include <stdio.h>
#include <stdlib.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 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,n,i);//打印每次排序的后果
    }
}

int main()
{
    int a[8] = {3,1,7,5,2,4,9,6};
    InsertSort(a,8);
    return 0;
}

二、折半插入排序算法
#include <stdio.h>
#include <stdlib.h>

void print(int a[],int n, int i){
    printf("%d:",i);
    for(int j=0;j<n;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;
}

三、2路插入排序算法
#include <stdio.h>
#include <stdlib.h>

void print(int a[],int n, int i){
    printf("%d:",i);
    for(int j=0;j<n;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、付费专栏及课程。

余额充值