排序算法(一) c语言

// main.c

#include <stdio.h>
#include "sortD.h"
#include "sortD.c"

#define N 12
int main() {
    RedType d[N]={{0, ' '}, {3,'l'},{6,'e'},{5,'v'},{2,' '},\
                   {11, '!'}, {9,'o'},{1,'I'},{7,' '},{10, 'u'},\
                   {4, 'o'}, {8,'y'}};
    SqList l1, l2;
    for(int i=0; i < N; i++) {
        l1.r[i] = d[i];
        l2.r[i] = d[i];
    }
    l1.length = N - 1;
    l2.length = N - 1;

    /*
    // Direct Insert sort
    printf("Before insert sort...\n");
    display(&l1);
    InsertSort(&l1);
    printf("After insert sort...\n");
    display(&l1);
    */

    // Binary Insert sort
    printf("Before insert sort...\n");
    display(&l1);
    BInsertSort(&l1);
    printf("After insert sort...\n");
    display(&l1);

    return 0;
}
// sortD.h
//

#ifndef SORT_SORTD_H
#define SORT_SORTD_H

#define MAXSIZE 30
typedef int KeyType;

// info data type struct
typedef char InfoType;

// record type struct
typedef struct{
    KeyType key;
    InfoType otherinfo;
}RedType;

// sequence list type
typedef struct{
    RedType r[MAXSIZE + 1];
    int length;
}SqList;

// less than
int lessthan(RedType *r1, RedType *r2){
    return r1->key < r2->key;
}

int lesseqthan(RedType *r1, RedType *r2){
    return r1->key <= r2->key;
}

// display
void display(SqList *l);

// Straight Insertion Sort
void InsertSort(SqList *l);

// Binary Insertion Sort
void BInsertSort(SqList *l);




#endif //SORT_SORTD_H
// sortD.c
//
#include "sortD.h"
#include <stdio.h>

void display(SqList *l){
    for(int i=1; i<(l->length+1); i++)
        printf("%c", l->r[i].otherinfo);
    printf("\n");
}
/*
 * Straight Insertion Sort
 * 复杂度取决于原排列的逆序数
 * O(n^2)
 */
void InsertSort(SqList *l){
    for(int i=2; i <=l->length; i++){
        if(lessthan(&(l->r[i]), &(l->r[i-1]))){
            l->r[0] = l->r[i];
            l->r[i] = l->r[i-1];
            int j;
            for(j=i - 2; lessthan(&(l->r[0]), &(l->r[j])); j--)
                l->r[j + 1] = l->r[j];
            l->r[j + 1] = l->r[0];
        }
    }
}

/*
 * Binary Insertion Sort
 * 由于之前为顺序表 可以采用折半插入来排序
 * 仅仅减少了比较次数,移动次数依旧是 n^2
 * O(n^2)
 */
void BInsertSort(SqList *l){
    for(int i=2; i <= l->length; i++){
        l->r[0] = l->r[i];
        int low = 1;
        int high = i;
        while(low <= high){ // has to be <=
            int m = (low + high) / 2;
            if(lesseqthan(&(l->r[0]), &(l->r[m]))) // has to be less equal
                high = m - 1;
            else
                low = m + 1;
        }
        for(int j=i - 1; j>=high + 1; j--)l->r[j+1] = l->r[j];
        l->r[high + 1] = l->r[0];
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值