Linear Merge Sort
I probably just blew your mind with the title, right? :D But no, I'm not kidding. Today it suddenly occurred to me that I can do a linear merge sort. However, there's a catch. I've shifted from serial programming to parallel programming.
Yesterday, I started learning about parallel programming on the GPU using CUDA, through an online course at Udacity (https://www.udacity.com/course/cs344). If you haven't heard of Udacity, it's an amazing website where you can learn a whole lot about computer science for the beautiful price of Free.
Now, here's my algorithm:
- Lets say my initial list is [a0, a1, ..., aN]
- The CPU then runs N/2 threads on the GPU that do the merging step of merge sort on pairs of elements of the list. a0 & a1, a2 & a3, ...
- Then the CPU runs N/(2^2) threads on the GPU that merge lists of size 2. [a0, a1] & [a2, a3], [a4, a5] & [a6, a7], ...
- Then the same with N/(2^3) threads on the GPU that merge lists of size 3.
- And so on until N/(2^(lg N)) threads on the GPU that do the final merging.
The CPU sends commands to the GPU lg N times. On the time it takes for the "i"th run of the GPU is at most the time it takes for 2*2^(i) comparisons since all of the merges happen at the same time. Hence, the time complexity of the entire program (disregarding the constant time it takes to copy array values from the CPU to the GPU and vice versa) can be calculated using the following equation:
