Advertisement
Guest User

Untitled

a guest
Sep 22nd, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1. // A divide and conquer based efficient solution to find median
  2. // of two sorted arrays of same size.
  3. #include<bits/stdc++.h>
  4. using namespace std;
  5.  
  6. int median(int [], int); /* to get median of a sorted array */
  7.  
  8. /* This function returns median of arr1[] and arr2[].
  9. Assumptions in this function:
  10. a. Both ar1[] and ar2[] are sorted arrays
  11. b. Both have n elements */
  12. int getMedian(int arr1[], int arr2[], int n)
  13. {
  14. /* return -1 for invalid input */
  15. if (n <= 0)
  16. return -1;
  17. if (n == 1)
  18. return (arr1[0] + arr2[0])/2;
  19. if (n == 2)
  20. return (max(arr1[0], arr2[0]) + min(arr1[1], arr2[1])) / 2;
  21.  
  22. int m1 = median(arr1, n); /* get the median of the first array */
  23. int m2 = median(arr2, n); /* get the median of the second array */
  24.  
  25. /* If medians are equal then return either m1 or m2 */
  26. if (m1 == m2)
  27. return m1;
  28.  
  29. /* if m1 < m2 then median must will be in arr1[m1....] and arr2[....m2] */
  30. if (m1 < m2)
  31. {
  32. if (n % 2 == 0)
  33. return getMedian(arr1 + n/2 - 1, arr2, n - n/2 +1);
  34. return getMedian(arr1 + n/2, arr2, n - n/2);
  35. }
  36.  
  37. /* if at all m1 > m2 then-> median must be in in arr1[....m1] and
  38. arr2[m2...] */
  39. if (n % 2 == 0)
  40. return getMedian(arr2 + n/2 - 1, arr1, n - n/2 + 1);
  41. return getMedian(arr2 + n/2, arr1, n - n/2);
  42. }
  43.  
  44. /* Function to get median of a sorted array */
  45. int median(int arr[], int n)
  46. {
  47. if (n%2 == 0)
  48. return (arr[n/2] + arr[n/2-1])/2;
  49. else
  50. return arr[n/2];
  51. }
  52.  
  53. int main()
  54. {
  55. int array1[] = {1, 2, 3, 6};
  56. int array2[] = {4, 6, 8, 10};
  57. int n1 = sizeof(array1)/sizeof(array1[0]);//to find the size of the array1
  58. int n2 = sizeof(array2)/sizeof(array2[0]);//to find the sizr of array2
  59. if (n1 == n2)
  60. printf("Median is %d", getMedian(array1, array2, n1));
  61. else
  62. printf("Doesn't work for arrays of unequal size");
  63. return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement