I saw an interview question on the Internet and thought it was a good idea. I 'd like to add it to my favorites.
What is a K-order array first?
Arrays with such features:
The I-th element is located between [I-K, I + k] After sorting.
K-order
Requirement: The test algorithm sorts a K-order array.
Solution:
According to the K-order array feature, there are obviously the following subsequences:
X [0], X [k + 1], X [2 (k + 1)], X [3 (k + 1)] ......
X [1], X [k + 1 + 1], X [2 (k + 1) + 1], X [3 (k + 1) + 1] ......
........................
X [K], X [k + 1 + K], X [2 (k + 1) + K], X [3 (k + 1) + k] ......
This k + 1 sub-sequence has been sorted, and the rest of the task isMerge
There are two methods:
Method 1: For a normal merge, the complexity is O (NK), which is the same as merging two arrays)
Method 2: Use the loser tree to merge the time when an element requires a logk and the time when n elements require O (nlogk ).