A quick fix would just add checks for end of arrays to the if used to compare the values in the arrays:
Code:
/* ... */
if((j >= &b[5]) || (i < &a[5]) && (*i < *j)){
c[k] = *i;
i++;}
else{
c[k] = *j;
j++;}
This adds the unneeded overhead of checking for the end of arrays on every loop. Note that std100093's example code also has this same unneeded overhead. You could put the checks after to reduce this. Since a large array can be sorted in a few seconds, the overhead of the extra checks isn't a big deal, but I provided example code with post checks below.
Originally Posted by
Quant89
Why should I use lists and not arrays?
You can implement "lists" as parts of an array.
Example merge array code with the checks after a move, using indexes instead of pointers. This code assumes that both a[] and b[] have at least one value. To handle the case where a[] or b[] start off with zero values, do a one time check at the start of the merge array code.
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[5]={1,5,6,10,13}, b[5]={4,8,9,10,14},c[10], i,j,k;
i = 0;
j = 0;
k = 0;
while(1){
if(a[i] < b[j]){
c[k++] = a[i++];
if(i >= 5){
do
c[k++] = b[j++];
while(j < 5);
break;
}
}
else{
c[k++] = b[j++];
if(j >= 5){
do
c[k++] = a[i++];
while(i < 5);
break;
}
}
}
for (k=0; k<10; k++)
printf("%d ",c[k]);
return 0;
}