Find median of two sorted Arrays

Hello, student today we learn about Finding the Median techniques using the Malloc in C Programming Language. The median is the part of the Middle in a Sorted number and maybe their type in ascending or descending order in an Array. Find median of two sorted arrays of different sizes in C.

Median of two sorted arrays

Array = [9,11,16,7,2]

Sorted array = [2,7,9,11,16]

#include <stdio.h>
#include <stdlib.h>
void swap (int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}

int main ()
{
int i, min_pos, k, j, m, med, mid, size;
float med1, val;
size=1;
int *arr=malloc(size*sizeof(int));

if (arr == NULL)
{
printf("Error! Mem not allocated");
exit (0);
}
printf ("Enter the no\n");
k=0;
int num=0;
do{
printf("Enter a number : ");
scanf ("%d", &num);
arr = realloc(arr, (size++) * sizeof(int));
if(num!=-1)
arr[k++]=num;

}
while(num!=-1);

//selection sort
for (i = 0; i < k - 1; i++)
{
min_pos = i;
//find min element
for (j = i + 1; j < k; j++)
{
if (arr[j] < arr[min_pos])
min_pos = j;

}
swap (&arr[min_pos], &arr[i]);
}

//find median
mid = k / 2;
if (k % 2 == 1)
{
val = arr[mid];
printf ("median is:%.1f", val);
}
else
{
med1 = (arr[mid - 1] + arr[mid]) / 2.0;
printf ("median is:%.1f", med1);
}

free(arr);
return 0;
}
Output

Enter a Number: 12

Enter a Number: 13

Median 12.5

Note:- You  keep entering the numbers and type -1 to terminate input.

How to sort an Array in C (clickHere)

2D Array Programs in C (clickHere)

Median of two sorted arrays program in C

In case you can’t figure it out, check this

Run 2

#include <stdio.h>

#include <stdlib.h>
void swap (int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}

 

int main ()
{
int i, min_pos, k, j, m, med, mid, size;
float med1, val;
size=1;
int *arr=malloc(size*sizeof(int));

if (arr == NULL)
{
printf(“Error! Mem not allocated”);
exit (0);
}
printf (“Enter the no\n”);
k=0;
int num=0;
do{
printf(“Enter a number : “);
scanf (“%d”, &num);
arr = realloc(arr, (size++) * sizeof(int));
if(num!=-1)
arr[k++]=num;

}
while(num!=-1);

//selection sort
for (i = 0; i < k – 1; i++)
{
min_pos = i;
//find min element
for (j = i + 1; j < k; j++)
{
if (arr[j] < arr[min_pos])
min_pos = j;

}
swap (&arr[min_pos], &arr[i]);
}

//find median
mid = k / 2;
if (k % 2 == 1)
{
val = arr[mid];
printf (“median is:%.1f”, val);
}
else
{
med1 = (arr[mid – 1] + arr[mid]) / 2.0;
printf (“median is:%.1f”, med1);
}

free(arr);
return 0;
}

Find median of two sorted arrays of different sizes

Output of Two sorted Arrayin C using selection short.

Enter a number : 12

Enter a number : 13

Enter a number : -1

median is:12.0

Median of two sorted arrays of different sizes

Find median of two sorted Arrays
Find median of two sorted Arrays

Median of Array in C

END

Leave a Reply

x