C ++程序查找元素的中位数,其中元素存储在2个不同的数组中
我们将考虑一个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