This is a merge- sort algorithm I wrote. Although, it works well for smaller arrays, it gives a segmentation fault for arrays containing more than 7/8 elements. It also fails in some cases where a number is repeated. For example - {5,5,1,2,1}. I have been trying to identify the error but to no avail
I know that the code is not completely efficient but I am concentrating on making it work right now. Suggestions regarding the improvements in the code will be helpful. Thank you in advance.
#include <iostream>
using namespace std;
void printarray(int a[], int size);
void splitsort(int b[], int start, int end); //Split array into half
void merge(int b[], int start, int end); // merge the sorted arrays
int main()
{
cout << "This is merge sort" << endl;
int array[] = { 9,8,7,6,5,4,3,2,1 };
int length = sizeof(array) / sizeof(array[0]);
printarray(array, length);
splitsort(array, 0, length - 1);
cout << "sorted array" << endl;
printarray(array, length);
return 0;
}
void printarray(int a[], int size) {
for(int i = 0; i<size; i++) {
cout << a[i] << ",";
}
cout << endl;
return;
}
void splitsort(int b[], int start, int end) {
//base case
if(end == start) { return; }
//
splitsort(b, start, (start + end) / 2);
splitsort(b, (start + end) / 2 + 1, end);
merge(b, start, end);
return;
}
void merge(int b[], int start, int end) {
int tempb[(end - start) + 1];
//base case
if(end == start) { return; } // if single element being merged
int i = start;
int j = (start + end) / 2 + 1;
for(int k = start; k <= end; k++) {
if(i == (start + end) / 2 + 1) { tempb[k] = b[j]; j++; }// finished first array
else if(j == end + 1) { tempb[k] = b[i]; i++; }// finished second array
else if(b[i] >= b[j]) {
tempb[k] = b[j];
j++;
}
else if(b[j] >= b[i]) {
tempb[k] = b[i];
i++;
}
}
for(int k = start; k <= end; k++) {
b[k] = tempb[k];
}
return;
}