I am trying to implement the Merge Sort algorithm. I am following the algorithm mentioned in the CLRS book.Here is my code
#include<stdio.h>
#include<stdlib.h>
void merge_sort(int *arr,int start_index,int end_index);
void merge(int *arr,int start_index,int middle_index,int end_index);
int main(){
int arr[]={5,2,1,6,0,3,3,4}; //8 elements last index 7
int i;
printf("Before sorting.\n");
for(i=0;i<8;i++)
printf("%d",arr[i]);
merge_sort(arr,0,7);
printf("\nAfter sorting.\n");
for(i=0;i<8;i++)
printf("%d",arr[i]);
return 0;}
void merge_sort(int *arr,int start_index,int end_index){
int middle_index;
if(start_index<end_index)
{
middle_index=(start_index+end_index)/2;
merge_sort(arr,start_index,middle_index);
merge_sort(arr,(middle_index+1),end_index);
merge(arr,start_index,middle_index,end_index);
}
}
void merge(int *arr, int start_index,int middle_index, int end_index){
int n1,n2,i,l,m;
n1=middle_index-start_index+2;
n2=end_index-middle_index+1;
int sub_arr1[n1],sub_arr2[n2];
for(i=0;i<(n1-1);i++)
sub_arr1[i]=arr[i];
for(i=0;i<(n2-1);i++)
sub_arr2[i]=arr[middle_index+1+i];
sub_arr1[n1+1]=100;
sub_arr2[n2+1]=100;
for(i=0;i<=end_index;i++){
l=0,m=0;
if(sub_arr1[l]<sub_arr2[m])
{arr[i]=sub_arr1[l++];}
else
{arr[i]=sub_arr2[m++];}
}}
I am getting the following output
Before sorting.
52160334
After sorting.
22222222
RUN FINISHED; exit value 0; real time: 10ms; user: 0ms; system: 0ms
Since I am taking small integers, I have taken 100 as the sentinel value
. I guess there is something wrong with the merge function. Any help appreciated.
The problem is very simple: your last loop
in the merge(...)
has a problem.
Move the l = 0
and m = 0
before the loop starts, because you are using the values 0 and 1 for l and m always, in each loop iteration.
Change it to:
int l=0, m=0;
for(i=0;i<=end_index;i++){
if(sub_arr1[l]<sub_arr2[m])
{arr[i]=sub_arr1[l++];}
else
{arr[i]=sub_arr2[m++];}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.