Solution: Find the Median of Two Sorted Arrays
In this review lesson, we give a detailed analysis of the solution to find the median of two sorted arrays.
We'll cover the following...
Solution #1: Brute Force
Press + to interact
double getMedian(int array1[], int array2[], int sizeOfArray1, int sizeOfArray2) {int arraySize = sizeOfArray1 + sizeOfArray2;int arraySizeMid = arraySize / 2;int i = 0;int j = 0;int count;int median = -1;int previousMedian = -1;for (count = 0; count <= arraySizeMid; count++) {previousMedian = median; // For even elements, we need to take the average of two medians and for that we are storing previous medianif (i != sizeOfArray1 && j != sizeOfArray2) {if (array1[i] > array2[j]) {median = array2[j];j++;}else {median = array1[i];i++;}}else if (i < sizeOfArray1) {median = array1[i];i++;}else {median = array2[j];j++;}}if (arraySize % 2 == 1) { // if the total size of the two arrays is oddreturn median;}else { // if the total size of the two arrays is evenreturn (median + previousMedian) / 2.0;}}int main() {// Example 1int array1[] = {900};int array2[] = {1, 5, 8, 10, 20};int sizeArray1 = sizeof(array1) / sizeof(array1[0]);int sizeArray2 = sizeof(array2) / sizeof(array2[0]);cout << "The median of the two arrays is: "<< getMedian(array1, array2, sizeArray1, sizeArray2);cout << endl << endl;// Example 2int array3[] = {900};int array4[] = {5, 8, 10, 20};int sizeArray3 = sizeof(array3) / sizeof(array3[0]);int sizeArray4 = sizeof(array4) / sizeof(array4[0]);cout << "The median of the two arrays is: "<< getMedian(array3, array4, sizeArray3, sizeArray4);return 0;}
We divide our algorithm into two cases:
For odd: Traverse both the arrays in such a way that you pick the minimum value from the current elements of both the arrays.
Remember to run the
for
loop for half the size of the totalarraySize
.
Keep the last value in median
.
For even: Median will be the average of the elements at index (( ...
Access this course and 1400+ top-rated courses and projects.