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

3 Answers3

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

Daniel
  • 7,357
  • 7
  • 32
  • 84
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.

DonO
  • 1,030
  • 1
  • 13
  • 27
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

Community
  • 1
  • 1
daBigBug
  • 343
  • 2
  • 11