码迷,mamicode.com
首页 > 编程语言 > 详细

归并排序---数组

时间:2015-04-16 01:27:56      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:

/*merge sort*/
#include <iostream>
using namespace std;

const int max_num = 1000000000;

void mergeData(int *s, int p, int q, int r)
{
    int n1 = q - p + 1;
    int n2 = r - q;
    int ld[n1 + 1];
    int rd[n2 + 1];
    int i = 0, j = 0, k = 0;
    for(i = 0; i < n1; i++)
    {
        ld[i] = s[p + i];
    }
    for(j = 0; j < n2; j++)
    {
        rd[j] = s[q + j + 1];
    }
    i = 0;
    j = 0;
    ld[n1] = max_num; // 哨兵
    rd[n2] = max_num;
    for(k = p; k <= r; k++)
    {
        if(ld[i] <= rd[j])
        {
            s[k] = ld[i];
            i++;
        }
        else
        {
            s[k] = rd[j];
            j++;
        }
    }
}

void mergeSort(int *s, int p, int r)
{
    int q = 0;
    if(p < r)
    {
        q = (p + r) / 2;
        mergeSort(s, p, q);
        mergeSort(s, q+1, r);
        mergeData(s, p, q, r);
    }
}

int main()
{
    int i = 0;
    int s[10] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
    mergeSort(s, 0, 9);
    for(i = 0; i < 10; i++)
    {
        cout << s[i] << " ";
    }
    cout << endl;
    return 0;
}

  

归并排序---数组

标签:

原文地址:http://www.cnblogs.com/xlzhh/p/4430716.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!