【问题标题】:Sorting a unique array in less than O(nlogn)Sorting a unique array in less than O(nlogn)
【发布时间】:2022-12-02 07:20:18
【问题描述】:

The question goes like this-

Assuming I have an Array of real numbers X[x1,...,xn] and a natural constant k such that for every i X[i]<X[i+k]. Write a sorting algorithm with time complexity better than O(nlogn). For the purpose of the question I am allowed to use quick sort, counting sort, Radix sort, bucket sort, heaps and so on.

All I've figured out so far is that if I take sublists by the remainder of the indecies (after dividing with K), those sublists are sorted. But merging them in the right complexity seems impossible. I also tried using min heaps after realizing the i smallest value must be in the first k*i places but it took me O(n^2) which is too much. I'd appreaciate any guidance/help/references. Thank you!

【问题讨论】:

  • When you say "unique array" do you mean that all the values in the array are unique (i.e. no duplicates)?
  • All I am given is that for every i X[i]<X[i+k] and that's what I meant by unique.

标签: algorithm sorting data-structures time-complexity


【解决方案1】:

Something to note here is that you essentially have m sorted arrays that you could merge directly. That is, the sequence [x[i],x[i+k],x[i+2k],x[i+3k]...] is sorted. As is [x[i+1],x[i+k+1],[x[i]+2k+1]...]

So you have to merge m sorted sequences, where m = n/k. The basic idea is:

  1. Initialize a priority queue of size k with the first item from each sorted sequence. That is, add x[0], x[1], x[2], x[3] ... x[k-1] to the priority queue. In addition, save the index of the item in the priority queue structure.
  2. Remove the first item from the queue and add the next item from that sequence. So if the first item you remove from the queue is x[3], then you'll want to add x[3+k] to the queue.
  3. You'll of course have to make sure that you're not attempting to add anything from beyond the end of the array.
  4. Continue in that fashion until the queue is empty.

    Complexity is O(n log m). Basically, every item is added to and removed from a priority queue of size m. Both addition and removal are, worst case, O(log m).

【讨论】:

    猜你喜欢
    • 2022-11-20
    • 2022-12-02
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 2019-03-22
    • 2021-07-11
    相关资源
    最近更新 更多