C++ Program to find Median of Elements where Elements are stored in 2 different arrays

C++Server Side ProgrammingProgramming

We shall consider a C++ program to find the median of elements where elements are stored in 2 different arrays.

Algorithm

Begin
   Function Median() has Two arrays a1[], a2[] and n = numbers of elements of the array as arguments:
   Initialize i and j by 0, and n1 and n2 by -1
   for c in range 0 to n, do
      if i = n, then
         n1 := n2
         n2 := a2[0]
      break the loop
      else if j = n, then
         n1 := n2
         n2 := a1[0]
      break the loop
      if a1[i] < a2[j], then
         n1 := n2
         n2 := a1[i]
         increase i by 1
      else
         n1 := n2
         n2 := a2[i]
         increase j by 1
      done
      return the average of n1 and n2.
End.

Example Code

#include<iostream>
#include <bits/stdc++.h>
using namespace std;
int Median(int a1[],int a2[], int n) {
   int i = 0;
   int j = 0;
   int c;
   int n1 = -1, n2 = -1;
   for (c = 0; c <= n; c++) {
      if (i == n) {
         n1 = n2;
         n2 = a2[0];
         break;
      }
      else if (j == n) {
         n1 = n2;
         n2 = a1[0];
         break;
      }
      if (a1[i] < a2[j]) {
         n1 = n2;
         n2 = a1[i];
         i++;
      } else {
         n1 = n2;
         n2 = a2[j];
         j++;
      }
   }
   return (n1 + n2)/2;
}
int main() {
   int n1,n2, i;
   cout<<"\nEnter the number of elements for 1st array: ";
   cin>>n1;
   int a1[n1];
   for(i = 0; i < n1; i++) {
      cout<<"Enter element for 1st array"<<i+1<<": ";
      cin>>a1[i];
   }
   cout<<"\nEnter the number of elements for 2nd array: ";
   cin>>n2;
   int a2[n2];
   for(i = 0; i < n2; i++) {
      cout<<"Enter element for 2nd array "<<i+1<<": ";
      cin>>a1[i];
   }
   if (n1 == n2)
      cout << "Median is "
      << Median(a1, a2, n1) ;
   else
      cout << "Doesn't work for arrays"
      << " of unequal size";
   return 0;
}

Output

Enter the number of elements for 1st array: 5
Enter element for 1st array1: 2
Enter element for 1st array2: 4
Enter element for 1st array3: 6
Enter element for 1st array4: 7
Enter element for 1st array5: 9
Enter the number of elements for 2nd array: 5
Enter element for 2nd array 1: 20
Enter element for 2nd array 2: 40
Enter element for 2nd array 3: 60
Enter element for 2nd array 4: 70
Enter element for 2nd array 5: 90
Median is 20
raja
Published on 04-Apr-2019 12:33:26
Advertisements