Home > database >  How to sort the indexes of an array in the fewest swaps
How to sort the indexes of an array in the fewest swaps

Time:02-06

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?

CodePudding user response:

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.

CodePudding user response:

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.

  •  Tags:  
  • Related