Thursday, 8 October 2015

get used to PROGRAMMING : Merge Sort



Hi, Lets see the solution to implement Merge Sort in C

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int* merge(int* Array1, int n, int* Array2, int m) 

 int x = m + n - 1; 
 int i = m-1; int j = n-1; 
 while (i >= 0 && j >= 0) 
 { 
  if (Array1[i] >= Array2[j]) 
  { 
   Array2[x] = Array1[i]; 
   i--; 
  } 
  else
  { 
   Array2[x] = Array2[j]; 
   j--; 
  } 
  x--; 
 } 
 if (i >= 0) 
  memcpy(Array2, Array1, (i + 1) * sizeof(int)); 
 return Array2; 
}
int main()
{
 int size;
 scanf("%d",&size);
 int array1[size];
 for(int i=0;i<size;i++)
    scanf("%d",&array1[i]);
 int array2[size+size];
 for(int i=0;i<size;i++)
    scanf("%d",&array2[i]);
 int *Output = merge(array1,size,array2,size);
 for(int i=0;i<size+size;i++)
 {
  printf("%d ",Output[i]);
 }
 return 0;
}

Output:

No comments:

Post a Comment