C语言实现思路
- 合并两个给出的数组
- 将合并后的数组按照从小到大的顺序进行排列
- 半段n1+n2个数的奇偶性
- 找到中指
#includeint Odd(int n);void orderIntegerArray(int *p, int n);double findMedianSortedArrays(int *numS1, int n1, int *sumS2, int n2);int main(void){ int nums1[9] = {3, 13, 7, 5, 21, 23, 23, 40, 23}; int nums2[5] = {14, 12, 56, 23, 29}; printf("The median is %lf\n", findMedianSortedArrays(nums1, 9, nums2, 5)); return 0;}double findMedianSortedArrays(int *numS1, int n1, int *numS2, int n2){ int *p, *q; p = numS1; q = numS2; int newArray[n1 + n2]; int *k; k = newArray; for (int i = 0; i < n1; i++) *(k + i) = *(p + i); for (int i = n1; i < n1 + n2; i++) *(k + i) = *(q + i - n1); orderIntegerArray(newArray, n1 + n2); for (int i = 0; i < n1 + n2; i++) printf("%d---", *(k + i)); putchar('\n'); double median; int n3 = n1 + n2; if (Odd(n3)) median = newArray[(n3 + 1) / 2 - 1]; else median = (newArray[n3 / 2 - 1] + newArray[n3 / 2 + 1 - 1]) / 2; return median;}void orderIntegerArray(int *p, int n){ int temp; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (*(p + i) > *(p + j)) { temp = *(p + i); *(p + i) = *(p + j); *(p + j) = temp; }}int Odd(int n){ if (n % 2 == 0) return 0;// even else return 1; // odd}
输出为:
3----5----7----12----13----14----21----23----23----23----23----29----40----56----
中值为: 22.000000