As part of an online course exercise, I was supposed to implement Merge Sort in C. Pointers were still not discussed prior to this exercise, so I have to work with arrays. Memory efficiency is not something I'm supposed to be focused on.
#include <cs50.h>
#include <stdio.h>
#define DEBUG
void getArray(int[], int);
void printArray(int[], int);
void mergesort(int[], int);
void merge(int[], int, int[], int, int[]);
int main(void)
{
printf("Length of array: ");
int len = GetInt();
int array[len];
getArray(array, len);
printf("Before sort: ");
printArray(array, len);
mergesort(array, len);
printf("After sort: ");
printArray(array, len);
return 0;
}
void getArray(int values[], int len)
{
for (int i = 0; i < len; i++)
{
printf("Number %i: ", i + 1);
values[i] = GetInt();
}
}
void printArray(int values[], int len)
{
for (int i = 0; i < len; i++)
{
printf("%i ", values[i]);
}
printf("\n");
}
void mergesort(int array[], int len)
{
if (len <= 1)
return;
// right side and left side lengths
int rlen, llen;
//calculate lengths of the half-arrays
rlen = len / 2;
llen = len - rlen;
int rhalf[rlen];
int lhalf[llen];
// copy first half of array into rhalf
for (int i = 0; i < rlen; i++)
{
rhalf[i] = array[i];
}
// copy the remainder of array into lhalf
for (int i = 0; i < llen; i++)
{
lhalf[i] = array[i + rlen];
}
#ifdef DEBUG
printf("len: %i\nrlen: %i\nllen: %i\n", len, rlen, llen);
printf("rhalf: ");
printArray(rhalf, rlen);
printf("lhalf: ");
printArray(lhalf, llen);
#endif
mergesort(rhalf, rlen);
mergesort(lhalf, llen);
merge(rhalf, rlen, lhalf, llen, array);
}
void merge(int rhalf[], int rlen, int lhalf[], int llen, int array[])
{
int i = 0, j = 0, k = 0;
// iterate over rhalf and lhalf until one counter reaches its end
while (i < rlen && j < llen)
{
if (rhalf[i] < lhalf[j])
{
array[k] = rhalf[i];
i++;
}
else
{
array[k] = lhalf[j];
j++;
}
k++;
}
// place the remaining elements (if any) in either half in their place
while (i < rlen)
{
array[k] = rhalf[i];
i++;
k++;
}
while (j < llen)
{
array[k] = lhalf[j];
j++;
k++;
}
#ifdef DEBUG
printf("merged: ");
printArray(array, llen + rlen);
#endif
}
What can I do to improve the code in terms of readability, style and performance?