Suppose you are given n red and n blue water jugs, all of different shapes and sizes. All red jugs hold different amounts of water, as do the blue ones. Moreover, there is a blue jug for every red jug that holds the same amount of water and vice versa. The task is to efficiently group the jugs into pairs of red and blue jugs that hold the same amount of water. (Problem Source: CLRS)

A simple solution to group the jugs into pairs is to compare a red jug with each blue jug. Once we get the matching pair, group that pair, and repeat for the next red jug. This algorithm can be easily implemented, but it will perform at most n2 comparisons.

We can do better by using a randomized algorithm where the expected number of comparisons is nlog(n). The idea is analogous to the randomized quicksort algorithm.
The expected number of comparisons performed by the above algorithm is the same as that of a randomized quicksort algorithm. ie. nlog(n). In the worst case, the largest jug gets picked every time, which results in n2 comparisons.

Below is the implementation in C++, Java, and Python based on the above idea.

C++

Download   Run Code

Output:

Red jugs : 2 3 6 7 8
Blue jugs : 2 3 6 7 8

Java

Download   Run Code

Output:

Red jugs : [2, 3, 6, 7, 8]
Blue jugs: [2, 3, 6, 7, 8]

Python

Download   Run Code

Output:

Red jugs : [2, 3, 6, 7, 8]
Blue jugs: [2, 3, 6, 7, 8]

Download   Run Code
Output:

Red jugs : 2 3 6 7 8
Blue jugs : 2 3 6 7 8

Download   Run Code
Output:

Red jugs : [2, 3, 6, 7, 8]
Blue jugs: [2, 3, 6, 7, 8]

Download   Run Code
Output:

Red jugs : [2, 3, 6, 7, 8]
Blue jugs: [2, 3, 6, 7, 8]

There are several other variations of this problem which can be solved similarly:

source