Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find median with minimum time in an array

I have an array lets say a = { 1,4,5,6,2,23,4,2}; now I have to find median of array position from 2 to 6 (odd total terms), so what I have done, I have taken a[1] to a[5] in arr[0] to arr[4] then I have sorted it and write the arr[2] as the median .

But here every time I put values from one array to another, so that the values of my initial array remains the same. Secondly, I have sorted, so this procedure is taking pretty much **time**. So I want to know if there is any way I can do this differently to reduce my computation time.

Any websites, material to understand, what, and how to do?

like image 206
Sudhanshu Gupta Avatar asked Jun 16 '12 16:06

Sudhanshu Gupta


People also ask

How do you find the median of an array in time?

To find the median of an unsorted array, we can make a min-heap in O(nlogn) time for n elements, and then we can extract one by one n/2 elements to get the median.

How do you find the median of time?

Finding the median in O(n log n) The most straightforward way to find the median is to sort the list and just pick the median by its index. The fastest comparison-based sort is O(nlogn) , so that dominates the runtime.

Can we calculate median without sorting?

You can certainly find the median of an array without sorting it. What is not easy is doing that efficiently. For example, you could just iterate over the elements of the array; for each element, count the number of elements less than and equal to it, until you find a value with the correct count.


2 Answers

Use std::nth_element from <algorithm> which is O(N):

nth_element(a, a + size / 2, a + size);
median = a[size/2];
like image 188
Mark Avatar answered Oct 27 '22 15:10

Mark


It is possible to find the median without sorting in O(n) time; algorithms that do this are called selection algorithms.

like image 20
Stephen Canon Avatar answered Oct 27 '22 15:10

Stephen Canon