数据结构 排序 归并排序

头文件:

#define MAXSIZE 20

#define EQ(a, b) ((a) == (b))
#define LT(a, b) ((a) < (b))
#define LQ(a, b) ((a) <= (b))

typedef 
int KeyType;

typedef 
int InfoType;

typedef 
struct {
    KeyType key;
    InfoType otherinfo;
}
RedType;

typedef 
struct {
    RedType r[MAXSIZE 
+ 1];
    
int length;
}
SqList;

源文件:

#include "sort.h"

#include 
"stdio.h"

void init(SqList &s, int w[], int n){
    s.length 
= n;
    
for(int i = 1; i <= n; i++){
        s.r[i].key 
= w[i - 1];
    }

}


void show(SqList s){
    
for(int i = 1; i <= s.length; i++){
        printf(
"%d ", s.r[i]);
    }

    printf(
" ");
}


//merge the sr[i...m] and sr[m+1...n] to tr[i...n].
void merge(RedType sr[], RedType tr[], int i, int m, int n){
    
int j, k;

    
for(j = m + 1, k = i; i <= m && j <= n; k++){
        
if(LQ(sr[i].key, sr[j].key)){
            tr[k] 
= sr[i++];
        }
else{
            tr[k] 
= sr[j++];
        }

    }


    
//copy the left of sr[i...m]
    if(i <= m){
        
for(int t = 0; t <= m - i; t++){
            tr[k 
+ t] = sr[i + t];
        }

    }


    
//copy the left of sr[m+1...n]
    if(j <= n){
        
for(int t = 0; t <= n - j; t++){
            tr[k 
+ t] = sr[j + t];
        }

    }

}


//merge sort sr and store in tr.
void mSort(RedType sr[], RedType tr[], int s, int t){
    
if(s == t){
        tr[s] 
= sr[s];
    }
else{
        
int m = (s + t)/2;
        RedType tr2[MAXSIZE
+1];

        mSort(sr, tr2, s, m);
        mSort(sr, tr2, m 
+ 1, t);
        merge(tr2, tr, s, m, t);
    }

}


void mergeSort(SqList &s){
    mSort(s.r, s.r, 
1, s.length);
}


void main(){
    
int w[] = {4938659776132749};
    
int n = 8;
        
    SqList s;
    init(s, w,  n);

    mergeSort(s);
    printf(
"after merge sort: ");
    show(s);
}

程序运行结果:

after merge sort:
13      27      38      49      49      65      76      97
Press any key to 
continue

 说明:

算法的复杂度为O(n * log(n)),是一种稳定的排序方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值