Friday, July 31, 2009

C++ Finding the median of a sorted array?

How do you find the median of an array, the middle value? If it is odd, then it is the middle value, if it's even, it's the average of the two middle values. How would you write that in code?

C++ Finding the median of a sorted array?
If my array had 8 values I'd do:





median = (array[8/2] + array[(8/2)-1])/2





Since your array ranges from 0-7 you want values 3 and 4 and this will give you those values.
Reply:Edit: I must have been dizzy when I read your question, I didn't noticed the word sorted in the question tagline, silly me. So ignore this.





The previous posters assumed you want the value of the median position. You probably want the median value. If that is the case you need to sort the array first, and then use the method described there.





There is many ways to sort an array (and even more for any stl containers)





Quicksort would be the sensible choice otherwise.


It's available through %26lt;stdlib.h%26gt; and %26lt;search.h%26gt;





void qsort( void *base, size_t num, size_t width, int (__cdecl *compare )(const void *elem1, const void *elem2 ) );





Look over to your compiler help documentation to see how to use it, or simply google qsort.
Reply:Below is the program for you in C++.





#include %26lt;iostream.h%26gt;





int main(int argc, char* argv[])


{


int arr[]={1,2,3,4,5,6};


int size=sizeof(arr)/sizeof(int);


int index=size/2;


float median=-1;





if((index % 2) == 0)


median=arr[index];


else


median=(float) (arr[index] + arr[index - 1]) / 2;





cout%26lt;%26lt;median;


return 0;


}


No comments:

Post a Comment