【发布时间】:2019-01-09 19:58:39
【问题描述】:
我需要为最多 100000 个整数的数组实现合并排序,但规范有点麻烦:我需要使用指向整数数组的指针、它的长度和一个额外的工作区数组进行合并,
mergesort 函数应如下所示:
void merge_sort(int *a, int *w, int n)
a 是要排序的,w 是用于合并的工作区,不能在我想要排序的对象之间使用数组和两个索引
伪代码:
merge_sort(int *a, int *w, int n) {
/* take care of stopping condition first */
if the array to be sorted has fewer than two elements then
return
merge_sort( first half of array a);
merge_sort( second half of array a);
merge the two halves of array a into array w
copy array w back into array a
}
merge(int *array, int *workspace, int len) {
initialise indices to point to the beginning of
the left and right halves of array
while there are elements in both halves of array {
compare the elements at the current left and right indices
put the smallest into workspace and increment both the index
it was taken from, and the index in workspace
}
add any remaining elements from left half of array to workspace
add any remaining elements from right half of array to workspace
}
这是我目前得到的:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ARRAY_MAX 100000
void merge_sort(int *a, int *w, int n) {
if (n == 1)
return;
else {
int *temp;
merge_sort(a, w, n / 2);
merge_sort(a + (n / 2), w, (n - (n / 2)));
/** Cannot figure what to pass to merge since it has to be the two halves
and how to copy contents of a to w **/
}
}
void merge(int *a, int *w, int n) {
/** Cannot figure this out **/
}
int main(void) {
int my_array[ARRAY_MAX];
int work_space[ARRAY_MAX];
int count = 0;
int i;
while (count < ARRAY_MAX && 1 == scanf("%d", &my_array[count])) {
count += 1;
}
start = clock();
merge_sort(my_array, workspace, count);
end = clock();
merge_sort(my_array, work_space, count);
for (i = 0; i < count; i++) {
printf("%d\n", my_array[i]);
}
fprintf(stderr, "%d %f \n", count, (end - start) / (double)CLOCKS_PER_SEC);
return EXIT_SUCCESS;
}
【问题讨论】:
-
另外,请阅读this question checklist 和idownvotedbecau.se 的所有内容,了解您的问题可能被否决的一些原因。最后请learn how to debug your programs.
-
向我们展示您尝试过哪些没有奏效。
-
@Sandy 请检查代码
标签: c arrays recursion merge mergesort