This is a mergesort implementation I wrote, trying to get back into C.
I am not so much interested in feedback on the optimality of the algorithm (as I could read up countless articles i'm sure), but deep criticism of my style would be greatly appreciated.
(The code works btw)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void mergesort_recurse(int* in_array, int i, int j);
void merge(int* array, int left, int centre, int right);
void mergesort(int* in_array, int len) {
mergesort_recurse(in_array, 0, len);
}
void mergesort_recurse(int* in_array, int left, int right) {
int length = right-left;
/*Base case: There are only two elements - Compare them and swap if
necessary.*/
if(length == 2) {
if(in_array[left] > in_array[right-1]) {
int temp = in_array[right-1];
in_array[right-1] = in_array[left];
in_array[left] = temp;
}
}
/*Leaves of lenth 1 can be ignored as they are already "sorted"*/
else if(length > 1){
/*Split into two and sort recursively.*/
int centre = left + length / 2;
mergesort_recurse(in_array, left, centre);
mergesort_recurse(in_array, centre, right);
merge(in_array, left, centre, right);
}
}
void merge(int* array, int left, int centre, int right) {
/*Establish the initial indexes of the left and right sides of the two
"halves" to be merged.*/
int l = left;
int r = centre;
int length = right-left;
/*A temporary array to hold the merged data - this implementation is not
in-place*/
int* tmp = malloc(length * sizeof(int));
/*Iterate over the length of the merge.*/
int i;
for(i = 0; i < length; i++) {
if(r==right){
/*If the right index has reached the right hand end of the data, the
remaining elements can be dumped in from the LHS.*/
memcpy(tmp+i, array+l, (length-i)*sizeof(int));
break;
}
else if (l==centre) {
/*Conversely if the left index has reached the LHS end, the
remaining elements can be dumped in from the RHS.*/
memcpy(tmp+i, array+r, (length-i)*sizeof(int));
break;
}
else if(array[l] < array[r]) {
/*Otherwise add from the left or right by comparison.*/
tmp[i] = array[l];
l++;
}
else {
tmp[i] = array[r];
r++;
}
}
/*Finally memcpy the temp array into the target.*/
memcpy(array+left, tmp, length*sizeof(int));
free(tmp);
}