Click here to Skip to main content
15,889,027 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I would like an efficient and non-invasive way of finding a median of a large array (a double array of size 300,000).

What I have tried:

I have tried an inefficient method:

double Median(double[] xs) {
  Array.Sort(xs);
  return xs[xs.Length / 2];
}


This sorts the original array which I don't want to have happen.
Posted
Updated 9-Dec-21 22:00pm
Comments
[no name] 9-Dec-21 19:32pm    
Since you have an "even" number of values, you will need "two" middle values to calculate the median.
Admin BTA 9-Dec-21 20:09pm    
Good point Gerry! I intended the size to be exemplary, it could be changing in real-time: sometimes even, sometimes odd. Since this method will be called often, I need it to be as efficient as possible.

You don't have a choice here. Median values, by definition, require an ordered set to find them.
 
Share this answer
 
Comments
Admin BTA 9-Dec-21 20:18pm    
Good point, Dave. With that said, I suppose the question is what is the most efficient way of sorting.
Dave Kreskowiak 9-Dec-21 20:33pm    
You're not going to do much better than the QuickSort and HeapSort algorithms Array.Sort already uses. Both use the IComparable interface to compare values though. This adds a bit of overhead to the algorithm, making it take a little bit longer.

You could implement your own QuickSort algorithm that doesn't depend on IComparable, but don't expect huge performance gains. We're talking about a few seconds better performance at best.
Admin BTA 9-Dec-21 22:08pm    
in my application, 7000 ticks can make a difference, so seconds could be a huge performance gain. good thought on the quicksort. thanks.
You could use the 'Median method in the open-source Math.NET Numerics library: [^].

For an interesting idea for an O(n) algorithm: [^] ... note: i have not used it.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900