Task 2: Find median in a 2D array
Write a function median_2d()that computes the median for a 2D numeric array (matrix). The inputs to the function are a pointer to the start of the array, and its dimensions (rows and cols). Your function should not modify the contents of the original matrix! The function prototype is given below.
float median_2d(float * ptr_array, int rows, int cols);
Domain knowledge:
The median is the middle number in a sorted, ascending or descending, list of numbers and can be more descriptive of that data set than the average.
If there is an odd amount of numbers, the median value is the number that is in the middle, with the same amount of numbers below and above.
If there is an even amount of numbers in the list, the middle pair must be determined, added together, and divided by two to find the median value.
Hint: In memory a 2D array is stored just like a 1D array.
#include<stdio.h>
float median_2d(float *ptr_array, int rows, int cols);
int main()
{
int rows,cols,i,j,n=0;
printf("Enter number of rows : ");
scanf("%d",&rows);
printf("Enter number of columns : ");
scanf("%d",&cols);
float arr[rows][cols];
printf("Enter the elements of array : ");\
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
scanf("%f",&arr[i][j]);
}
}
float arr1[rows*cols],*ptr;
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
arr1[n]=arr[i][j];
n=n+1;
}
}
ptr=arr1;
printf("Median = %f",median_2d(ptr,rows,cols));
return 0;
}
float median_2d(float *ptr_array, int rows, int cols)
{
float min,max,temp,median;
int i,j;
for (i = 0; i < rows*cols; ++i)
{
for (j = i + 1; j < rows*cols; ++j)
{
if (ptr_array[i] > ptr_array[j])
{
temp = ptr_array[i];
ptr_array[i] = ptr_array[j];
ptr_array[j] = temp;
}
}
}
if((rows*cols)%2!=0)
{
median=ptr_array[rows*cols/2];
}
else
{
int n=((rows*cols-1)/2);
median=(ptr_array[n]+ptr_array[n+1])/2;
}
return median;
}
Comments
Leave a comment