merge_sort不工作,输出只是一堆1 -1和0

时间:2017-01-12 11:07:01

标签: c algorithm mergesort

所以我得到了以递归方式编写merge_sort的任务,它只返回与原始输入长度相同的0,-1, 1数组。我做错什么的想法? input_merge_sort.h input_merge_sort.c 由任务给出并处理输入和输出,因此我必须关注的是算法本身。关于算法的一些细节,以确保我理解正确:

MergeSort通过将列表拆分为相同大小的列表,将它们拆分为单个元素,然后将2个单元素列表放在一起,比较它们并将较小的列表放在前面来对列表进行排序。使用子列表,通过读取2个子列表,比较值和进一步放置指针1元素,将其写入原始列表,然后将其与另一个子列表的旧元素进行比较,该元素比另一个更大。

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "input_merge_sort.h"
/*
    array:  Pointer at the start of the array
    first:  Index of the first element
    len  :  Index of the last element
*/

void merge(int a[], int i1, int j1, int j2) {
    int temp[j2 - i1];    //array used for merging
    int i, j, k;
    i = i1;    //beginning of the first list
    int i2 = j1 + 1;
    j = i2;    //beginning of the second list
    k = 0;

    while (i <= j1 && j <= j2) {    //while elements in both lists
        if (a[i] < a[j])
            temp[k++] = a[i++];
        else
            temp[k++] = a[j++];
    }

    while (i <= j1)    //copy remaining elements of the first list
        temp[k++] = a[i++];

    while (j <= j2)    //copy remaining elements of the second list
        temp[k++] = a[j++];

    //Transfer elements from temp[] back to a[]
    for (i = i1, j = 0; i <= j2; i++, j++)
        a[i] = temp[j];
}

void merge_sort(int *array, int first, int last) {
    int middle;
    if (first < last) {
        middle = ((first + last) / 2);
        merge_sort(array, first, middle);
        merge_sort(array, middle + 1, last);
        merge(array, first, middle, last);
    }
}

/*
Reads integers from files and outputs them into the stdout after mergesorting them.

How to run: ./introprog_merge_sort_rekursiv <max_amount>  <filepath>
*/
int main(int argc, char *argv[]) {
    if (argc != 3) {
        printf("usage: %s <max_amount>  <filepath>\n", argv[0]);
        exit(2);
    }

    char *filename = argv[2];

    // Initialize array
    int *array = (int*)malloc(atoi(argv[1]) * sizeof(int));        //MINE
    int len = read_array_from_file(array, atoi(argv[1]), filename);

    printf("Input:\n");
    print_array(array, len);

    // Call of "merge_sort()"
    merge_sort(array, array[0], array[len - 1]); //MINE

    printf("Sorted:\n");
    print_array(array, len);
    free(array);
    return 0;
}

1 个答案:

答案 0 :(得分:1)

函数merge_sort接受一个数组,并将其第一个和最后一个元素的索引作为参数,但是您自己传递元素。变化:

merge_sort(array, array[0],array[len-1]);

为:

merge_sort(array, 0, len - 1);

merge中,您在堆栈上创建一个临时数组,但它只是一个元素短。它应该是:

int temp[j2 - i1 + 1];

我建议您更改这些函数,以便它们不会将最后一个元素作为上限但是该范围之外的第一个元素,就像在C数组和循环中一样。在我看来,这使代码更简单。然后,数组的两半是[low, mid)[mid, high)。整个数组的长度为high - low