'How to sort the indexes of an array in the fewest swaps

So say you are given an array with only letters A, B, and C.

A is larger than B, B is larger than C.

Now say you have to rearrange all the indexes in order, so that all A's appear before B, followed by C in the fewest possible swaps.

For example, [A,A,C,A,B] would require 2 swaps, first C and B, then A and B.

How would you create a program that would count the minimum amount of swaps required?



Solution 1:[1]

You can user a counter variable to keep track of the swaps. Whenever the swap happens you can increment the counter variable. At the end what ever the the counter is that many swaps have occurred. You can also compare variables for equality and leave the swap and count happening.

Solution 2:[2]

The answer is if you need to swap those letters or not.

If Yes - just count them with simple counter.

If No - then the easiest solution is to create copy of the array and swap elements there and use Yes option. But if you cannot create extra array it will be pretty harder from my point of view. You need to store somewhere which letter was "replaced" and probably a number of As in that array but that is just a guess.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pauan
Solution 2 Vojt?ch VĂ¡chal