加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

C语言归并排序法实现二维数组[1列(数值),2列(下标)]按照第一列排序

(2016-04-22 01:23:21)
标签:

it

分类: 工作
[专业排序速度检测]
http://www.sorting-algorithms.com
打开网页后,点击左边的或则上边的按钮,就会看到排序速度效果

[C语言代码]


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

void Merge(int (*sourceArr)[2],int (*tempArr)[2], int startIndex, int midIndex, int endIndex)

{

    int i = startIndex, j=midIndex+1, k = startIndex;

    while(i!=midIndex+1 && j!=endIndex+1)

    {

        if(sourceArr[i][0] >= sourceArr[j][0])

        {

            tempArr[k++][0] = sourceArr[j++][0];

            tempArr[k-1][1] = sourceArr[j-1][1];

        }

        else

        {

            tempArr[k++][0] = sourceArr[i++][0];

            tempArr[k-1][1] = sourceArr[i-1][1];

        }

    }

    while(i != midIndex+1)

    {

        tempArr[k++][0] = sourceArr[i++][0];

        tempArr[k-1][1] = sourceArr[i-1][1];

    }

    while(j != endIndex+1)

    {

        tempArr[k++][0] = sourceArr[j++][0];

        tempArr[k-1][1] = sourceArr[j-1][1];

    }

    for(i=startIndex; i<=endIndex; i++)

    {

        sourceArr[i][0] = tempArr[i][0];

        sourceArr[i][1] = tempArr[i][1];

    }

}

 

//内部使用递归

void MergeSort(int (*sourceArr)[2], int (*tempArr)[2], 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);

    }

}

int main(int argc, char * argv[])

{

  // 假设二维数组的第二维是下标

  int a[8][2] = {{50,0}, {10,1}, {20,2}, {30,3}, {70,4}, {40,5}, {80,6}, {60,7}};

    int i, b[8][2];

    MergeSort(a, b, 0, 7);

    //升序排列取后六个即可

    for(i=2; i<8; i++)

      printf("(%d ,%d) ", a[i][0],a[i][1]);

    printf("\n");

    return 0;

}


Output:

1

(30 ,3) (40 ,5) (50 ,0) (60 ,7) (70 ,4) (80 ,6) 

[辅助工具]
在线C语言编译
http://www.52bcx.com/compile.htm

耗时情况如下

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有