हम तत्वों के माध्यिका को खोजने के लिए एक C++ प्रोग्राम पर विचार करेंगे जहां तत्वों को 2 अलग-अलग सरणियों में संग्रहीत किया जाता है।
एल्गोरिदम
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.
उदाहरण कोड
#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; }
आउटपुट
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