Wednesday, August 17, 2011

QUES 18 Merge Sort


C LANGUAGE BOOK








WAP TO MERGE TWO ARRAY.THE ELEMENT AND SIZE OF ARRAYS SHOULD BE ENTERED BY THE USER.

















#include<stdio.h>

#define SIZE1 100
#define SIZE2 100
#define SIZE3 200

void Bub1_Sort(int q, int a[]);
void MERGARR(int x,int a[],int y,int b[],int r, int c[]);

int main()
{
int i,q1,q2,q3;
int a1[SIZE1],a2[SIZE2];
int r[SIZE3];

/* how many number will be entered */

printf("\n\nHow Many Number Will Be Entered For The First Array:");
  scanf("%d", &q1);

for(i = 0; i < q1; i++)
{
 printf("\ni = %d \t a = ", i + 1);
 scanf("%d", &a1[i]);
}

for(i = 0; i < q1; i++)
{
 printf("\ni = %d \t a = %d ", i+1,a1[i]);
}

printf("\n\nHow Many Number Will Be Entered For The Second Array:");
  scanf("%d", &q2);

for(i = 0; i < q2; i++)
{
 printf("\ni = %d \t a = ", i + 1);
 scanf("%d", &a2[i]);
}
for(i = 0; i < q2; i++)
{
 printf("\ni = %d \t a = %d ", i+1,a2[i]);
}

/* Sort the elment using BubbleSort */

printf("\nSort The First Array Using BubbleSort\n");
 Bub1_Sort(q1, a1);

printf("\nSort The Second Array Using BubbleSort\n");
 Bub1_Sort(q2, a2);

/* Display the Sorted numbers */
clrscr();

     printf("THE FIRST ARRAY IS:\n");
      for(i = 0;i < q1;i++)
       printf("\ni = %d \t a = %d ", i+1,a1[i]);
       printf("\n");
     printf("THE SECOND ARRAY IS:\n");
      for(i = 0;i < q2;i++)
       printf("\ni = %d \t a = %d ", i+1,a2[i]);
       printf("\n");

q3 = q1+q2;

 MERGARR(q1, a1, q2, a2, q3, r);

      printf("THE MERGING ARRAY IS:\n");
      for(i = 0;i < q3;i++)
       printf("\ni = %d \t a = %d ", i+1,r[i]);
       printf("\n");
}

void Bub1_Sort(int q,int a[])
{
 int i,j,k,temp;

 for(j = q-1; j > 0; j--)
 {
 for(k = q-1; k > 0 ; k--)
 {
   if(a[k] < a[k-1])
   {
   temp = a[k-1];
   a[k-1] = a[k];
   a[k] = temp;
   }

 }


}
 return;
}


void MERGARR(int x,int a[],int y,int b[],int r, int c[])
{
 int i,j,k,temp;
 int alimit,blimit,climit;
 alimit = x;
 blimit = y;
 climit = r;

 printf("\nx = %d", x);
 printf("\ny = %d", y);
 printf("\nr = %d\n", r);

 if((x+y)!=r)
 {
 printf("\nArray not compatible");
 exit(1);
 }
 i=0;
 j=0;

 for(k=0; i<=alimit && j<=blimit;k++)
     if(a[i] < b[j])
       c[k] = a[i++];
     else
      c[k] = b[j++];


 return;
}






C LANGUAGE BOOK

No comments:

Post a Comment