Hello Everyone,
Im trying to implement merge sort. Currently Im trying to split the array[] in the prototype to induvidual arrays with one element. Im having a segmentation fault. In the console it keeps outputting the "I have been called statment" Which i put in to help me troubleshoot. Now I know for a fact that the array has 20 elements (comming from a text file) I have even printed all 20 elements and it stops after the last one. Can anyone please help me to find an error in my code?
Go gently, im new to this. This is a school lab, but my prof is of no help with programming because he says its an algorithms course but we are also being asked to program. Recursion is also new to me.
Thank you!
Code:
#include "mySort.h"
#include <stdio.h>
#include <stdlib.h>
/**********************
Algorithm to Implement
MergeSort (Array(First..Last))
Begin
If Array contains only one element
Then Return Array
Else
Middle= ((Last + First)/2) rounded down to the nearest integer
LeftHalfArray = MergeSort(Array(First..Middle))
RightHalfArray = MergeSort(Array(Middle+1..Last))
ResultArray = Merge(LeftHalfArray, RightHalfArray)
Return ResultArrayEndIfEnd MergeSort
**********************/
void mySort(int array[], unsigned int first, unsigned int last)
{
/*Declare variables*/
int middle;
int size = last - first + 1;
int arrayLeft[(size/2)];
int arrayRight[(size/2)];
/*Check if array contains one element*/
if (first == last)
return;
/*If array contains more then 1 element, split them*/
middle = (int) (size/2);
printf ("I have been called, the middle is %d \n", middle) ;
mySort(arrayLeft, first, middle);
mySort(arrayRight, (middle + 1), last);
}