Skip to content

Function to calculate median of two sorted arrays. - #75

Open
Bhavyajain21 wants to merge 5 commits into
sagar2002malik:masterfrom
Bhavyajain21:master
Open

Function to calculate median of two sorted arrays.#75
Bhavyajain21 wants to merge 5 commits into
sagar2002malik:masterfrom
Bhavyajain21:master

Conversation

@Bhavyajain21

@Bhavyajain21 Bhavyajain21 commented Oct 14, 2021

Copy link
Copy Markdown

resolve #1
Fixes #1

@Shikhar007-bot

Copy link
Copy Markdown

`double median(int arr1[], int arr2[], int n, int m) {
// If the arrays are empty, return -1.
if (n == 0 || m == 0) {
return -1;
}

// Merge the two arrays into a new array.
int *mergedArray = new int[n + m];
int i = 0, j = 0, k = 0;
while (i < n && j < m) {
if (arr1[i] <= arr2[j]) {
mergedArray[k++] = arr1[i++];
} else {
mergedArray[k++] = arr2[j++];
}
}

// Copy the remaining elements of arr1 to mergedArray.
while (i < n) {
mergedArray[k++] = arr1[i++];
}

// Copy the remaining elements of arr2 to mergedArray.
while (j < m) {
mergedArray[k++] = arr2[j++];
}

// Calculate the median of the merged array.
int medianIndex = (n + m) / 2;
if ((n + m) % 2 == 0) {
// If the number of elements is even, the median is the average of the two middle elements.
return (mergedArray[medianIndex - 1] + mergedArray[medianIndex]) / 2.0;
} else {
// If the number of elements is odd, the median is the middle element.
return mergedArray[medianIndex];
}
}
int main() {
int arr1[] = {1, 3, 5, 7, 9};
int arr2[] = {2, 4, 6, 8, 10};

int n = sizeof(arr1) / sizeof(arr1[0]);
int m = sizeof(arr2) / sizeof(arr2[0]);

double median = median(arr1, arr2, n, m);

printf("The median of the two arrays is: %f\n", median);

return 0;
}
`
this is the c++ code for calculating median of 2 sorted arrays

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Write any program in C, C++, Java, Python

2 participants