【转】C语言之二路归并排序

    在学习数据结构导论,考试中有二路归并排序法(归并排序(MERGE-SORT)是建立在归并操作上的一种有效的排序算法,该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。若将两个有序表合并成一个有序表,称为二路归并。),转算法如下:

    

/*
 ============================================================================
 Name        : MergeSort.c
 Author      : zlj
 Version     :
 Copyright   : soft.rz
 Description : Hello World in C, Ansi-style
 ============================================================================
 */

#include <stdlib.h>
#include <stdio.h>

int k=1;

void Merge(int sourceArr[],int tempArr[], int startIndex, int midIndex, int endIndex)
{
    int i = startIndex, j=midIndex+1, k = startIndex;
    while(i!=midIndex+1 && j!=endIndex+1)
    {
        if(sourceArr[i] > sourceArr[j])
            tempArr[k++] = sourceArr[j++];
        else
            tempArr[k++] = sourceArr[i++];
    }
    while(i != midIndex+1)
        tempArr[k++] = sourceArr[i++];
    while(j != endIndex+1)
        tempArr[k++] = sourceArr[j++];
    for(i=startIndex; i<=endIndex; i++)
        sourceArr[i] = tempArr[i];
    for (i=startIndex; i<=endIndex; i++)
    	printf("%d  ", sourceArr[i]);
    printf("\n");
}

//内部使用递归
void MergeSort(int sourceArr[], int tempArr[], int startIndex, int endIndex)
{
    int midIndex;
    if(startIndex < endIndex)
    {
        midIndex = (startIndex + endIndex) / 2;
        MergeSort(sourceArr, tempArr, startIndex, midIndex);
        MergeSort(sourceArr, tempArr, midIndex+1, endIndex);
        Merge(sourceArr, tempArr, startIndex, midIndex, endIndex);
    }
    printf("\nThe %d Times\n", k);
    k++;
}

int main(int argc, char * argv[])
{
    int a[15] = {50, 10, 20, 30, 70, 40, 80, 60, 45, 66, 38, 29, 51,74, 13};
    int i, b[15];
    printf("原始数据: \n");
    for(i=0; i<15; i++)
        printf("%d ", a[i]);
    MergeSort(a, b, 0, 14);
    printf("\n\n排序后的数据: \n");
    for(i=0; i<14; i++)
        printf("%d ", a[i]);

    return 0;
}

执行结果如下:

原始数据: 
50 10 20 30 70 40 80 60 45 66 38 29 51 74 13 
The 1 Times

The 2 Times
10  50  

The 3 Times

The 4 Times

The 5 Times
20  30  

The 6 Times
10  20  30  50  

The 7 Times

The 8 Times

The 9 Times
40  70  

The 10 Times

The 11 Times

The 12 Times
60  80  

The 13 Times
40  60  70  80  

The 14 Times
10  20  30  40  50  60  70  80  

The 15 Times

The 16 Times

The 17 Times
45  66  

The 18 Times

The 19 Times

The 20 Times
29  38  

The 21 Times
29  38  45  66  

The 22 Times

The 23 Times

The 24 Times
51  74  

The 25 Times

The 26 Times
13  51  74  

The 27 Times
13  29  38  45  51  66  74  

The 28 Times
10  13  20  29  30  38  40  45  50  51  60  66  70  74  80  

The 29 Times


排序后的数据: 
10 13 20 29 30 38 40 45 50 51 60 66 70 74 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值