【发布时间】:2022-12-01 20:30:08
【问题描述】:
i can't understand the problem in my code, can anyone explain to me where the problem in my code please. the book where i got my algorithm:Introduction to Algorithms, Third Editioni understand how the algorithm work but in coding it, its sort only the 4 first number and keep the other without sorting.
code:
`
#include <stdio.h>
void sortArr(int *nums,int arrSize){
// nums[start...end]
// nums[start...mid] n1
// nums[mid+1...end] n2
int start, mid, end;
start = 0;
end = arrSize-1;
mid = (end+start)/2;
int n1, n2;
n1 = mid-start+1;
n2 = end - mid;
int l[n1], r[n2];
for(int i=0;i<n1;i++){
l[i] = nums[start+i];
}
for(int i=0;i<n2;i++){
r[i] = nums[mid+1+i];
}
int i, j;
i =0;
j = 0;
for(int k=start;k<arrSize;k++){
if(l[i]<=r[j]){
nums[k] = l[i];
i++;
}else{
nums[k] = r[j];
j++;
}
}
}
int main(){
int arr[] = {3, 41, 52, 26, 38, 57, 9, 49};
int arrsize = sizeof(arr)/sizeof(arr[0]);
printf("before sorting: \n");
for(int i=0;i<arrsize;i++){
printf("%d ", arr[i]);
}
sortArr(arr, arrsize);
printf("\n after sorting: \n");
for(int i=0;i<arrsize;i++){
printf("%d ", arr[i]);
}
return 0;
}
`
【问题讨论】:
-
Debugger.......
-
Without looking at the code or the book: check array indexing! In pseudocode it often starts at 1, in C at 0.
-
I used the starting index in 0 and changed other index to work with the index 0 instead of 1
-
For mergesort, you need to sort the two halves before merging. And it's not your problem yet, but using a VLA for the two halves will only work for small arrays
-
Also your merge is wrong (it produces out-of-range reads) in the case when one of the two halves is used up. The algorithm in the book adds +infinity to both halves to prevent this, although this is not how I'd actually write it in C.
标签: c algorithm sorting mergesort