0

I have to answer the following question:

What sorting algorithm is recommended if the first n-m part
is already sorted and the remaining part m is unsorted? Are there any algorithms that take O(n log m) comparisons? What about O(m log n) comparisons?

I just can't find the solution.

My first idea was insertion sort because O(n) for almost sorted sequence. But since we don't know the size of m the Runtime is very likely to be O(n^2) eventough the sequence is half sorted already isn't it?

Then I tought perhabs its quick sort because it takes (Sum from k=1 to n) Cavg (1-m) + Cavg (n-m) comparisons. But after ignoring the n-m part of the sequence the remaining sequence is 1-m in quicksort and not m.

Merge Sort and heap sort should have a runtime of O(m log m) for the remaining sequence m I would say.

Does anyone have an idea or can give me some advice?

Greetings

Dennis
  • 3
  • 1
  • Because this is a pure algorithmic question, it may better suit [cs.se] (but remember to read their help center before asking) / Besides, it's impossible to get less than the time for reading the sequence which is already O(n). – user202729 May 14 '18 at 08:11
  • 1
    If you know which part is sorted, sort only the rest and than merge the two sorted parts. – MrSmith42 May 14 '18 at 08:24

2 Answers2

2

Have you tried sorting remaining part m separately as O(m log (m)) complexity (with any algorithm you like: MergeSort, HeapSort, QuickSort, ...) and then merge that part with sorted part using MergeSort (You won't even need to fully implement MergeSort - just single pass of it's inner loop body to merge two sorted sequences)?

That would result in O(m*log(m) + n + m) = O(m*log(m) + n) complexity. I don't believe it is possible to find better asymptotic complexity on single-core CPU. Although it will require additional O(n+m) memory for merging result array.

Sasha
  • 8,537
  • 4
  • 49
  • 76
0

Which sort algorithm works best on mostly sorted data?

Sounds like insertion and bubble are good. You are free to implement as many as you want then test to see which is faster/fewer operations by supplying them partially sorted data.

Shefeto
  • 178
  • 1
  • 10