-1

What is the most efficient sorting algorithm to sort an Array, that has n elements and EVERY element originally is 10 position away from its position after sorting?

I am thinking about insertion sort, but I have no clue how to proof that:

(1) It is the most efficient.

(2) The algorithm needs in worst case O(n) steps to sort the Array.

A self-conceived example: [10,11,12,13,14,15,16,17,18,19,0,1,2,3,4,5,6,7,8,9,]

greybeard
  • 2,249
  • 8
  • 30
  • 66

2 Answers2

3

With these constraints there are not that many possibilities:

The value at index 0 must go to index 10 as that is the only index that is 10 positions away from index 0. And which value can move to index 0? It can only be the value that is currently at index 10. So it's a swap between indexes 0 and 10.

With the same reasoning the value at index 1 will swap with the value at index 11, and 2 with 12, 3 with 13, ... 9 with 19.

So now we have covered all indices in the range 0..19. No values outside this range will get into this range, nor will any value in this range move out of it. All movements involving these indices are already defined above.

We can repeat the same reasoning for indices in the range 20..39, and again from positions 40..59, ...etc

So we can conclude:

  • The array's size is necessarily a multiple of 20
  • Only one permutation is possible that abides to the given rules
  • The solution is therefore simple.

Solution in pseudo code:

sort(A):
    for i = 0 to size(A) - 1 step 20:
        swap A[i+0..i+9] with A[i+10..i+19]

In some languages the swap of such array slices can be done very efficiently.

trincot
  • 317,000
  • 35
  • 244
  • 286
  • This is correct if all of the elements are distinct; I'm not sure the question makes sense otherwise ("its position" implies each element has only one possible position once the array is sorted) but maybe worth noting this assumption. – kaya3 Jun 09 '21 at 07:36
0

When you say 10 positions away, the actual position could be i - 10 or i + 10. So, just make a temporary copy of the array and take minimums for each 10 index positions away.

This is because the only clash we can assume is some index going for +10 and another index going for -10 for some same index j. So taking minimums will install correct value at the index j.

private static void solve(int[] arr){
        int[] temp = new int[arr.length];
        Arrays.fill(temp,Integer.MAX_VALUE);
        for(int i=0;i<arr.length;++i){
            if(i - 10 >= 0) temp[i - 10] = Math.min(temp[i - 10],arr[i]);
            if(i + 10 < temp.length) temp[i + 10] = Math.min(temp[i + 10],arr[i]);
        }
        
        for(int i=0;i<arr.length;++i) arr[i] = temp[i];
 }
nice_dev
  • 17,053
  • 2
  • 21
  • 35