1

Hello everybody I would like to ask for your opinion. What algorithm would you advice for sorting arrays A with most four numbers that are in wrong place and obtain an efficient asymptotic running time? I was thinking for an insertion sort, but is there something better if there are at most four elements? Thanks in advance

2
  • Pick the 4 out-of-order elements, sort them, merge with the rest of the elements. (or perform an insertion-sort variant) Commented Dec 7, 2016 at 19:17
  • Look at adaptive sorts like Smoothsort and hybrids like Timsort Commented Dec 7, 2016 at 19:20

3 Answers 3

1

if the array has at most 4 elements in wrong place, the insertion sort (with binary search implementation) can do the job well, but the best thing to do is get all wrong elements and sort them, for example

1 2 A 4 B 6 C 7

if A, B and C are wrong, you can just sort them and realloc into the array:

1 2 C 4 A 6 B 7

and as there are just a few elements, you can build an array with them and use selection sort and put them back in the right place on the original array

Sign up to request clarification or add additional context in comments.

1 Comment

Best solution posted so far.
0

Given the size of the array I don't think the choice of algorithm would make a difference. I would say quick sort. Pick the second number as a pivot and go from there.

Comments

0

For smaller arrays, almost all sorting techniques roughly have the same running time. In fact, if the array is partially sorted, insertion sort works the best. You can see a gif comparison here.

Also, this question has already been answered here

Comments

Your Answer

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.