Answer to Question #199300 in C for Hassam

Question #199300

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


1
Expert's answer
2021-05-27T06:24:42-0400
#include <stdio.h>
float median_2d(int col,float ptr_array[][col],int row){
    float b[9];
    int temp,k=0,i=row,j=col;
    
    for(i=0;i<row;i++)
	    for(j=0;j<col;j++) 
     	    b[k++]=ptr_array[i][j]; 
    
    for (i=0;i<row*col;i++){ 
 	    for (j=0;j<(row*col-1-i);j++){ 
   	        if(b[j]>b[j+1]){ 
	         	temp = b[j]; 
	        	b[j] = b[j+1]; 
		        b[j+1] = temp; 
	        } 
	    } 
    }
    k=0; 
    for(i=0;i<row;i++) 
    { 
	    for(j=0;j<col;j++) 
	    { 
	        ptr_array[i][j]=b[k]; 
	        k++; 
	    }
    }
    for(i=0;i<row;i++) 
    { 
	    for(j=0;j<col;j++) 
	    { 
            printf("%.2f ",ptr_array[i][j]); 
	    } 
    	printf("\n"); 
    }
    if((row*col)%2!=0){
        float median=(row*col)/2;
        median=median+1;
        return b[(int)median];
    }
    else{
        int med=(row*col)/2;
        med=((b[med-1]+b[med])/2);
        return (float)med;
    }
        
}
int main(){
    float arr[3][2]={{3.3,2.2},{6.6,5.5},{9.9,8.9}};
    for(int i=0;i<3;++i) 
    { 
	   for(int j=0;j<2;++j) 
	   { 
	       printf("%.2f ",arr[i][j]); 
	   } 
	   printf("\n"); 
    }
    printf("\n");
    float median=median_2d(2,arr,3);
    printf("\nmedian=%.2f",median);
    return 0;
}
    

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS