I want to sort an array .
SO i wrote this merge sort, it doesnt do what i want it to i.e sort, just stalls !
im going over the algorithm again and again, and i feel this is so correct, but no !
please take a look and tell me what might be wrong.
void mergeSort(int *arr, int low, int high){
int mid = (low+high)/2;
while(low<high){
mergeSort(arr, low, mid);
mergeSort(arr, mid+1, high);
merge(arr, low, high, mid);
}
}
void merge(int *arr,int low, int high, int mid){
int i =low,j=mid+1,k=0;
int temp[50]; // should i new/malloc this with size of ( high -low +1) ?
while(i<=mid && j<=high){
if(arr[i]<arr[j])
temp[k++] = arr[i++];
else
temp[k++] = arr[j++];
}
while(i<=mid)
temp[k++] = arr[i++];
while(j<=high)
temp[k++] = arr[j++];
for(int x = 0; x<=high; x++){
arr[x]=temp[x];
}
}
if the loop is entered at all, it is an infinite loop since neither
lownorhighare changed.Yes, you should definitely allocate the correct amount of storage.
That should better be
arr[i] <= arr[j]to have a stable sort, though that doesn’t matter forints.That should be
for(int x = low; ....arr[x] = temp[x-low];(or use two indices).