【发布时间】:2017-05-27 11:12:38
【问题描述】:
所以我得到了以递归方式编写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;
}
【问题讨论】:
-
非常相似this
-
当您从
main调用merge_sort时,您会传递数组和两个索引,但您传递的是数组及其第一个和最后一个元素。 -
int temp[j2-i1];-->int temp[j2-i1 +1];