2つのソートされた配列の中央値
中央値は中央値です。つまり、中央値は順序付きリストの中央値です。累積パーセンテージ50%に相当します。
2つの配列のサイズは同じである必要があります。最初に、2つの別々の配列の中央値を見つけ、次に別々の中央値を比較して、2つのリストの実際の中央値を取得します。
入力と出力
Input:
Two sorted array are given.
Array 1: {1, 2, 3, 6, 7}
Array 2: {4, 6, 8, 10, 11}
Output:
The median from two array. Here the median value is 6.
Merge the given lists into one. {1, 2, 3, 4, 6, 6, 7, 8, 10, 11}
From the merged list find the average of two middle elements. here (6+6)/2 = 6. アルゴリズム
中央値(リスト、n)
入力: データのリストとデータの数。
出力: 指定されたリストの中央値。
Begin if the list has even number of data, then return (list[n/2] + list[n/2-1])/2 else return list[n/2] End
findMedian(list1、list2、n)
入力- 2つのソートされたリスト、およびリストの数。
出力- 2つのソートされたリストの中央値。
Begin if n <= 0, then it is invalid, and return invalid number if n = 1, then return (list1[0] + list2[0])/2 if n = 2, then return ((max of list1[0], list2[0]) + (min of list1[1], list2[1]))/2 med1 := median(list1, n) med2 := median(list2, n) if med1 = med2, then return med1 if med1 < med2, then if item has even number of data, then subList := data from list2, from 0 to n/2 – 1 data return findMedian(subList, list1, n – (n/2) + 1) subList := data from list2, from 0 to n/2 data return findMedian(subList, list2, n – (n/2)) End
例
#include<iostream>
using namespace std;
int median(int list[], int n) {
if (n%2 == 0) //when array containts even number of data
return (list[n/2] + list[n/2-1])/2;
else //for odd number of data
return list[n/2];
}
intfindMedian(int list1[], int list2[], int n) {
if (n <= 0)
return -1; //invalid length of lists
if (n == 1)
return (list1[0] + list2[0])/2; //for single element simply get average from two array
if (n == 2)
return (max(list1[0], list2[0]) + min(list1[1], list2[1])) / 2;
int med1 = median(list1, n); //Find median from first array
int med2 = median(list2, n); //Find median from second array
if (med1 == med2) //when both medians are same, they are the final median
return med1;
if (med1 < med2) {
if (n % 2 == 0)
return findMedian(list1 + n/2 - 1, list2, n - n/2 +1);
return findMedian(list1 + n/2, list2, n - n/2);
}
if (n % 2 == 0) //when med1 > med2
return findMedian(list2 + n/2 - 1, list1, n - n/2 + 1);
return findMedian(list2 + n/2, list1, n - n/2);
}
int main() {
int list1[] = {1, 2, 3, 6, 7};
int list2[] = {4, 6, 8, 10, 11};
int n1 = 5;
int n2 = 5;
if (n1 == n2)
cout<< "Median is "<<findMedian(list1, list2, n1);
else
cout<< "Doesn't work for lists of unequal size";
} 出力
Median is 6
-
JavaScriptで配列の中央値を計算する
以下は、JavaScriptで配列の中央値を計算するためのコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> &nbs
-
配列のソートされた個別の要素をC言語で出力します
整数要素の配列が与えられた場合、タスクは重複する値を削除し、ソートされた方法で個別の要素を出力することです。 以下に示すのは、整数型の値を4、6、5、3、4、5、2、8、7、0の形式で格納する配列です。結果は、ソートされた要素を0、2、3、4として出力します。 4、5、5、6、7、8ですが、この結果には重複する値4と5が含まれているため、削除する必要があり、最終結果は0、2、3、4、5、6、7、8になります。 例 Input: array[] = {4, 6, 5, 3, 4, 5, 2, 8, 7, 0} Output: 0 2 3 4 5 6 7 8 説明 したがって、結果を達成