When i try to run my code using using recursion i get stuck in an infinite loop.
this is my first time implementing divide and conquer using recursion so i am a bit rusty on the concepts. Please have a look at the code an let me know where i can correct it.
/**
* MergeSort.c
*
* Ujjwal Arora
*
*
* Implements merge sort for an array
*/
#include<stdio.h>
#include<conio.h>
void merge(int array[6],int beg,int mid,int end);
void mergesort(int array[6],int beg,int end);
void display(int array[6]);
int main(void)
{
// Initializes the array
int array[6]={3,1,2,9,5,4};
// Initialize the beginning and the end
int beg=0, end=5;
// Implement the Merge Sort
mergesort(array,beg,end);
getch();
}
void mergesort(int array[6],int beg,int end) //Calls Initial merge sort
{
int mid;
if(beg<end)
{
mid=(beg+end)/2;
mergesort(array,beg,mid); //Left part of the array
mergesort(array,mid+1,end); //Right part of the array
merge(array,beg,mid,end); //merge two sorted arrays
}
}
void merge(int array[6],int beg,int mid,int end)
{
int temp[6]; //Declare a temp array for storing the sorted data
//Initialize the temp array
int k=beg;
//initialize the pointers for two sub arrays
int i=beg;
int j=mid;
while(i<=mid && j<=end)
{
if(array[i] < array[j])
{
temp[k]=array[i];
i++;
}
else
{
temp[k]=array[j];
j++;
}
k++;
}
//Clearing any remaining elements in the sub array
if(i>mid)
{
for(int m=j;j<=end;m++)
{
temp[k]= array[m];
k++;
}
}
else
{
for(int m=i;m<=mid;m++)
{
temp[k]= array[m];
k++;
}
}
//Reassign the sorted elements to the original array
for(k=beg;k<end;k++)
{
array[k]=temp[k];
}
display(array); //display array
}
void display(int array[6])
{
for(int i=0;i<6;i++)
{
printf("%d ",array[i]);
}
printf("\n");
}