I stumbled across the median of medians algorithm when I was looking for an efficient way to calculate the nearest 20 cities to any city, given their latitude and longitude.
It is a selection algorithm that has a worstcase O(n) complexity for selecting the kth order statistic (kth smallest number) in an unsorted array with length n.
Say you have an unsorted array and you would like to pick the fourth smallest element. One approach would be to just sort the array and pick the fourth element. However, the best case performance for this approach is O(nlogn).
The algorithm
 If n is negligible, e.g. n <= 5, sort the array and return the kth element. (The complexity of sorting small arrays is linear).
 Partition the array into subarrays of length 5.
 Sort each subarray and select the median of each.
 Recursively find the median of the medians you found in 3.
 Loop through all n1 elements, comparing them with the median of medians m and create two arrays left and right, where left contains all elements < m and right contains all elements > m
 From 5, we can infer that the position of m, p = L + 1, where L is the length of left. In other words, m is the (L + 1)th smallest element.
 If k == p, return m.
 If k < p, return the kth smallest element of left.
 If k > p, then return the (k – p)th smallest element of right.
An example
Given an array of length n = 10: [10, 6, 8, 3, 7, 1, 2, 4, 9, 5], we would like to find the kth smallest element, where k = 3.
 Split the array into two subarrays of size 5: [10, 6, 8, 3, 7] and [1, 2, 4, 9, 5].
 Sort each subarray and select the medians: [3, 6, 7, 8, 10] and [1, 2, 4, 5, 9], medians 7 and 4.
 Pick the median of the two medians m = 4.
 Loop over the initial array splitting it into two arrays:
left = [3, 1, 2] and right = [10, 6, 8, 7, 9, 5].  The position of m, p = left.length + 1
 Since k < p we recursively find the kth smallest element of left.
 Since left.size <= 5, we follow step 1: sort the array and return the kth element, 3.
The code
Since I tagged this post with ‘TDD’ We’ll need to write a few test cases first. My favorite testing framework for ruby is currently rspec with guard.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 

Then we fix the breaking specs by writing the lib:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 

You can find the complete code on github