Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

addedAlgo #75

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions c/Median of two sorted arrays of same size.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@

#include <stdio.h>

/* This function will return median of ar1[] and ar2[].
given the two arrays are sorted and are of size n
*/
int getMedian(int ar1[], int ar2[], int n)
{
int i = 0; /* Current index of array ar1[] */
int j = 0; /* Current index of array ar2[] */
int count;
int m1 = -1, m2 = -1;

/* Since there are 2n elements, median will be mean
of elements at index n-1 and n in the array obtained after
we merge both the arrays */
for (count = 0; count <= n; count++)
{
/*Below is to handle case where all elements of ar1[] are
smaller than all the elements of ar2[]*/
if (i == n)
{
m1 = m2;
m2 = ar2[0];
break;
}

/*Below is to handle case where all elements of ar2[] are smaller than all the elements of ar1[]*/
else if (j == n)
{
m1 = m2;
m2 = ar1[0];
break;
}
/* this is condition when two arrays have some common elements */
if (ar1[i] <= ar2[j])
{
m1 = m2; /*will store the prev median */
m2 = ar1[i];
i++;
}
else
{
m1 = m2; /* will store the prev median */
m2 = ar2[j];
j++;
}
}

return (m1 + m2)/2;
}

/* main program for above functions */
int main()
{
int ar1[] = {1, 12, 15, 26, 38};
int ar2[] = {2, 13, 17, 30, 45};

int n1 = sizeof(ar1)/sizeof(ar1[0]);
int n2 = sizeof(ar2)/sizeof(ar2[0]);
if (n1 == n2)
printf("Median is %d", getMedian(ar1, ar2, n1));
else
printf("The arrays are of unequal size");
getchar();
return 0;
}