Answer to Question #198594 in C for Frhan

Question #198594

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);


1
Expert's answer
2021-05-25T15:25:57-0400
#include <stdio.h>
#include <stdlib.h>

#define ROWS_COUNT 3
#define COLS_COUNT 3

void swap(float* a, float* b)
{
    float temp;
    temp = *a;
    *a = *b;
    *b = temp;
}

void sort(float* ptr_array, size_t size)
{
    size_t i, j;

    for(i = 0; i < size - 1; ++i)
    {
        for(j = 0; j < size - i - 1; ++j)
        {
            if(ptr_array[j] > ptr_array[j + 1])
            {
                swap(&ptr_array[j], &ptr_array[j + 1]);
            }
        }
    }
}

float median_2d(float* ptr_array, int rows, int cols)
{
    size_t i, size;
    float result;
    float* copy_array;

    size = rows * cols;
    
    copy_array = (float*) malloc(size * sizeof(float));

    for(i = 0; i < size; ++i)
    {
        copy_array[i] = ptr_array[i];
    }

    sort(copy_array, size);

    result = size % 2 ? copy_array[size / 2]
                      : (copy_array[size / 2 - 1] + copy_array[size / 2]) / 2;

    free(copy_array);
    
    return result;
}

int main()
{
    float matrix[ROWS_COUNT * COLS_COUNT] = {4.0f, 6.0f, 5.0f,
                                             1.0f, 3.0f, 2.0f,
                                             7.0f, 9.0f, 8.0f};

    printf("The median value is: %f\n", median_2d(matrix, ROWS_COUNT, COLS_COUNT));

    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