Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

sorting and combining two arrays

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
I am a beginner C programmer and am faced with the following problem. I need to have two arrays, of varying sizes, then to sort them (using bubble, insertion, or a selection sort) using a function that combines the two sorted arrays into a third array that contains all of the elements from the two arrays already sorted. Sorry for the confusing wording, but any help you all could give me would be greatly appreciated. Thanks.
 
#include <stdlib.h>
#include <stdio.h>

#define ELEMS( array )( sizeof( array )/sizeof( array[0]))

void BubbleSort( int*,int );
void OutArray( int*,int );
void MergeArrays( int*,int*,int*,int,int );

int main( void )
{
int iFirst []={ 5,2,1,4,3 };
int iSecond[]={ 7,6,10,9,8,11,13,12 };
int iSumElems;
int* iBuffer;

iSumElems=ELEMS( iFirst )+ELEMS( iSecond );
iBuffer =calloc( iSumElems,sizeof( int ) );

BubbleSort( iFirst,ELEMS( iFirst ) );
BubbleSort( iSecond,ELEMS( iSecond ) );

MergeArrays( iBuffer,iFirst,iSecond,ELEMS( iFirst ),ELEMS( iSecond ) );
OutArray( iBuffer,iSumElems );

free( iBuffer );

return 0;
}

void BubbleSort( int* iArray,int iSize )
{
int iPass;
int bExchanges;
int iIndex;
int iTemp;
int i;

iTemp =0;
iPass =0;
iIndex =0;
bExchanges=1;

while( iPass < iSize && bExchanges==1 )
{
bExchanges=0;
for( i=0;i<iSize-1;i++ )
{
if ( iArray > iArray[i+1] )
{
iTemp =iArray;
iArray =iArray[i+1];
iArray[i+1]=iTemp;
bExchanges =1;
}

}

}

}

void MergeArrays( int* iBuffer,int* iFirst,int* iSecond,
int iSizeFirst,int iSizeSecond )
{
int i;
for( i=0;i<iSizeFirst;i++ )
iBuffer=iFirst;

for( i=0;i<iSizeSecond;i++ )
iBuffer[i+iSizeFirst]=iSecond;
}

void OutArray( int* iArray,int iSize )
{
int i;
for( i=0;i<iSize;i++ )
printf( &quot;%d\n&quot;,iArray );
}

//Note that the ELEMS macro can only determine the # of
//elements in an array (not a pointer) if the arrays
//declaration is visible.

Mike L.G.
mlg400@blazemail.com
 
You might want to add some error checking code also... Mike L.G.
mlg400@blazemail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top