欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

排序算法三:归并排序

程序员文章站 2022-03-24 13:48:34
...

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

#define LEN 20

void merge(int *num, int start, int mid, int end)
{
    int len1 = mid - start + 1;
    int len2 = end - mid;
    int left[len1], right[len2];
    int i, j, k;

    for (i = 0; i < len1; i++)
        left[i] = num[start + i];
    for (j = 0; j < len2; j++)
        right[j] = num[mid+1+j];

    i = j = 0;
    k = start;
    while (i < len1 && j < len2) {
        if (left[i] < right[j])
            num[k++] = left[i++];
        else
            num[k++] = right[j++];
    }

    while (i < len1)
        num[k++] = left[i++];
    while (j < len2)
        num[k++] = right[j++];
}

void sort(int *num, int start, int end)
{
    int mid;
    if (start < end) {
        mid = (start + end)/2;
        sort(num, start, mid);
        sort(num, mid+1, end);
        merge(num, start, mid, end);
    }
}

void show(int *num, int len)
{
    int i;
    for (i = 0; i < LEN; i++)
        printf("%3d", num[i]);
    printf("\n");
}

int main(int argc, char *argv[])
{
    int num[LEN], i;
    srand(time(NULL));
    for (i = 0; i < LEN; i++)
        num[i] = rand() % 100;

    show(num, LEN);
    sort(num, 0, LEN-1);
    show(num, LEN);

    return 0;
}

 

上一篇: countsort.c

下一篇: 归并排序总结