how do i write a c program to merge sort 2 already sorted arrays?
Write a c program to merge sort 2 already sorted arrays?
Here is a small programme that will merge two sorted arrays of integer. You'll have to tweek it if you want to merge a different numeric type, and to add error checking -- I left all error checking out to make the code clearer.
#include %26lt;stdlib.h%26gt;
int *merge( int *a, int *b, int len )
{
int ai = 0; /* index into each array */
int bi = 0;
int *m = NULL;
int *mp = NULL;
mp = m = (int *) malloc( sizeof( int ) * len * 2); /* merged result*/
while( ai %26lt; len %26amp;%26amp; bi %26lt; len ) /* until one source is exhausted*/
{
if( *(a+ai) %26lt; *(b+bi) )
*mp++ = *(a+ai++);
else
*mp++ = *(b+bi++);
}
/* tack on the remainder of the array that was not exhausted */
while( ai %26lt; len )
*mp++ = *(a+ai++ );
while( bi %26lt; len )
*mp++ = *(b+bi++ );
return m; /* the merged array goes back to caller */
}
main( int argc, char **argv )
{
int first[] = { 1, 4, 8, 10, 12, 16, 22 };
int second[] = { 3, 6, 9, 12, 15, 18, 21 };
int *merged;
int i;
merged = merge( first, second, 7 );
for( i = 0; i %26lt; 14; i++ )
printf( "%d ", merged[i] );
printf( "\n" );
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment