Sort a Large Array Using Multiple Threads
xAISoftware Engineer · OnsiteLast updated
This question evaluates understanding of concurrent programming, parallel algorithm design, sorting algorithms, and merging techniques under multi-threaded execution, focusing on thread-safety, deterministic correctness despite scheduling variability, and performance trade-offs.
Sort a Large Array Using Multiple Threads
You are given a large array of integers nums and a thread count k. Sort the array in ascending order using multiple threads, structured as follows:
- Partition the array into
kcontiguous chunks of (nearly) equal size. - Sort each chunk concurrently, one worker thread per chunk, using your language's real threading primitives (e.g.,
threading.Threadin Python,std::threadin C++,Thread/ExecutorServicein Java). Each thread may use any standard comparison sort on its own chunk. - Merge the
ksorted chunks into one fully sorted array. The merge must not simply re-sort the concatenated data: it must exploit the fact that the chunks are already sorted. The intended approach is a k-way merge using a min-heap (priority queue), which mergesntotal elements acrossksorted runs inO(n log k)time.
Return (or print, per the judge's I/O format) the fully sorted array.
Requirements
- The
kchunk sorts must actually run on separate threads; the main thread must wait for all workers to finish before merging. - The final result must be deterministic and correct regardless of thread scheduling order. Threads must not write to shared state without clear ownership (each worker should own exactly its chunk).
- Target overall work:
O(n log n)total sorting work split across threads, plus anO(n log k)merge. - Handle edge cases:
kgreater than the array length, an empty array, and arrays with duplicate values.
Example
nums = [5, 2, 9, 1, 7, 3], k = 2
Chunks: [5, 2, 9] [1, 7, 3]
After parallel
chunk sorts: [2, 5, 9] [1, 3, 7]
k-way merge: [1, 2, 3, 5, 7, 9]
Output: [1, 2, 3, 5, 7, 9]
Constraints
0 <= n <= 10^6elements, each in the signed 32-bit integer range.1 <= k <= 16.- Duplicates are allowed and must all appear in the output.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.