关闭

归并排序

179人阅读 评论(0) 收藏 举报
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#define MAXSIZE 100
#define ARRAYSIZE 8
void mergeSort(int*, int);
void _mergeSort(int*, int, int);
//合并
void merge(int*, int, int, int);
//复制
void copy(int*, int*, int, int);
int main(void)
{
    int i;
    int array[ARRAYSIZE]= {666, -1023, 68, 2 ,1000, 999, 9, -999};
    mergeSort(array, ARRAYSIZE);
    for (i = 0; i < ARRAYSIZE; ++i)
    {
        printf("%d ", array[i]);
    }
    printf("\n");
    return 0;
}
void mergeSort(int *array, int length)
{
    if (NULL == array || 0 == length)
    {
        return ;
    }
    _mergeSort(array, 0, length - 1);
}
void _mergeSort(int *array, int begin, int end)
{
    if (begin >= end)
    {
        return ;
    }
    int middle = begin + ((end - begin) >> 1);
    _mergeSort(array, begin, middle);
    _mergeSort(array, middle + 1, end);
    merge(array, begin, middle, end);
}
//将a[begin, middle]和a[middle + 1, end]归并
void merge(int *array, int start, int middle, int end)
{
    int length = end - start + 1;
    int b[length];
    memset(b, 0, sizeof(int) * length);
    int left = start;
    int right = middle + 1;
    int all = 0;
    while(right <= end && left <= middle)
    {
        if(array[left] < array[right])
        {
            b[all] = array[left];
            ++left;
        }
        else
        {
            b[all] = array[right];
            right ++;
        }
        ++all;
    }
    /* move the left data */
    if(left <= middle)
    {
        memmove(&b[all], &array[left], sizeof(int) * (middle - left + 1));
    }
    if(right <= end)
    {
        memmove(&b[all], &array[right], sizeof(int) * (end - right + 1));
    }
    memmove(&array[start], b, sizeof(int) * length);
    /*
    all = 0;
    for (i = start; i <= end; ++i)
    {
        array[i] = b[all];
        ++all;
    }
    */
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:130132次
    • 积分:3883
    • 等级:
    • 排名:第8132名
    • 原创:293篇
    • 转载:22篇
    • 译文:0篇
    • 评论:11条
    文章分类
    最新评论