Correctness Of Minimum Number Of Swaps To Sort An Array

情到浓时终转凉″ 提交于 2019-12-04 21:06:27

Starting at the first element in the unsorted array, check if it is in the correct place, if not swap the correct value into that position. The test can either be done as you did by comparing to a sorted version of the collection, or the selected element can be compared to each element that follows it.

As you go along you may encounter elements that are in the correct position - either because they started in the correct place or they were swapped there when placing an earlier element (the last element must be by the time all other ones have been placed). Just leave those in place and move to the next element.

With this method every swap places at least one element correctly, some swaps will correctly place both.

An element in a correct place can be discounted from the problem - there is never a need to move it from its correct place to sort any other elements. Also a pair of elements that in each others places (e.g. 3 and 1 in {3,2,1} ) never need to be swapped with any of the other elements. They form their own independent set of elements.

Once you have a method, as above, for obtaining the correct answer, it can obviously be used to evaluate any alternative method.

Index :   0   1   2   3   4   5   6   7   8   9
------+-----+---+---+---+---+---+---+---+---+--
Array :   1  22  32  42  12  83  64  93  73  53
------+-----+---+---+---+---+---+---+---+---+--
          A  BBBBBBBBBBBBBB  CC  DD  CCCCCCCCCC
Target:   0   2   3   4   1   8   6   9   7   5
Diffs :   0   1   1   1  -3   3   0   2  -1  -4
Source:   0   4   1   2   3   9   6   8   5   7

In this example, the array[] needs to be sorted.

  • Target is the index where this position should go after the sort
  • source is the position where this index shoul get its value from
  • diffs is the relative movement that the item at this index does during the sort

You can see four (cyclic) groups:

  • A : 1 member 1
  • B : 4 members {22,32,42,12}
  • C : 4 members: {83,93,73,53}
  • D : 1 member: 64

The groups with 1 member are already sorted: zero swaps needed. The groups with 4 members can be sorted with 4 swaps each. (the final swap puts two elements to their final place) So the number of swaps needed is 0+3+3+0

Now you only need to prove that you can sort an N-cycle in N-1 swaps...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!