1
$\begingroup$

Problem:

Given $S$ — a sorted array where some of the elements were randomly changed, assuming that you're provided with an $S_1$ — an array of indexes of changed elements. Design an algorithm that will sort the array in $O(n)$ time.

Additionally, we know that $\text{length of }S_1\le\log_2(\text{length of }S)$.

Example:

$S$ — [3, 5, 7, (20), 15 ,(0) ,16]

$S_1$ — [3, 5]

() - Changed elements

Question:

I have some troubles designing the algorithm. My first idea was to just use Count or Radix sort algorithm, but as the values which are changed can be random I've ruled out count sort as potential candidate.

The second idea is to:

  1. Load the values based on indexes of $S_1$ into new array $S_x$.

  2. Rewrite $S$ without the elements of indexes provided in $S_1$.

  3. Sort $S_x$.

  4. Use "Merge" procedure from Merge Sort on $S_x$ and $S$.

However that still will leave me with $O(n\log n)$ as I'll need to sort $S_x$ array. I'll appreciate any advice on the approach.

Yuval Filmus
281k27 gold badges317 silver badges514 bronze badges
asked Apr 27, 2018 at 13:50
$\endgroup$
1
  • $\begingroup$ Sorting the array $S_x$ takes $O(m\log m),ドル where $m = |S_1|$. Since $m \leq \log n,ドル sorting $S_x$ takes time $O(\log n\log\log n)$. So this strategy actually works under the much weaker assumption $|S_1| = O(|S|/\log |S|)$. $\endgroup$ Commented Apr 27, 2018 at 15:21

2 Answers 2

2
$\begingroup$

Note the length of $S_1$ is no more than $\log_2n,ドル so the time you need to sort $S_x$ is $O(\log n\log\log n),ドル which is $O(n)$.

answered Apr 27, 2018 at 15:19
$\endgroup$
1
$\begingroup$

If you are given the indices, it is trivial. Sort the indices. Remove the changed elements into a separate array and pack the first one together. Sort the changes elements and merge with the first array. All in O(n) as long as the number of changed elements is O(n / log n).

Much more difficult if you don’t know which elements are changed.

answered Apr 27, 2018 at 17:26
$\endgroup$
1
  • $\begingroup$ You must sort the whole array if you dont know the changed elements, is there better solution? $\endgroup$ Commented Apr 28, 2018 at 18:41

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.