Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,907 questions

51,839 answers

573 users

How to find the median of an int array in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>

int compare(const void* a, const void* b) {
    return *(int*)a - *(int*)b;
}

double find_median_of_int_array(int array[], int size) {
    qsort(array, size, sizeof(int), compare);

    for (int i = 0; i < size; i++) {
        printf("%d ", array[i]);
    }

    double median;

    if (size % 2 == 0) {
        median = (array[size / 2 - 1] + array[size / 2]) / 2.0;
    }
    else {
        median = array[(size) / 2];
    }

    return median;
}

int main()
{
    int array[] = { 40, 70, 60, 55, 90, 45, 100, 80, 65, 50, 82, 58 }; // (60 + 65) / 2
    
    /*  int array[] = {24, 25, 26, 27, 28, 30, 32, 51, 34, 35, 36, 40, 60, 42, 49};
        24 25 26 27 28 30 32 34 35 36 40 42 49 51 60
        median = 34.00
    */

    int size = sizeof(array) / sizeof(array[0]);

    double median = find_median_of_int_array(array, size);

    printf("\nmedian = %.2f", median);

    return 0;
}



/*

40 45 50 55 58 60 65 70 80 82 90 100
median = 62.50

*/

 



answered Jul 17, 2024 by avibootz

Related questions

1 answer 71 views
1 answer 83 views
1 answer 89 views
2 answers 63 views
2 answers 146 views
1 answer 98 views
1 answer 98 views
...