Given array \$A\$ \$(a_0, a_1,... , a_n) \$ as a permutation of \$(0, 1,...,n)\$ where \$n ≥ 2\$. Sort array \$A\$ into array \$(0, 1,...,n\$) with \$2\$ caveats:
- \$1\$ swap is counted when swapping a non-zero value and \$0\$ in the array \$A\$. This is the only allowed way to swap.
- Swap as few times as possible.
The array will always be scrambled.
Sample I/O
Print only \$1\$ output if many equally optimal solutions exist.
Input and output format is flexible.
Input:
2 3 0 1 5 4
Output:
2 3 1 3 4 5 4
Visualization
Original A array: 2 3 0 1 5 4
1. (2): 0 3 2 1 5 4 #Swapped 2 and 0
2. (3): 3 0 2 1 5 4 #Swapped 3 and 0
3. (1): 3 1 2 0 5 4 #Swapped 1 and 0
4. (3): 0 1 2 3 5 4 #Swapped 3 and 0
5. (4): 4 1 2 3 5 0 #Swapped 4 and 0
6. (5): 4 1 2 3 0 5 #Swapped 5 and 0
7. (4): 0 1 2 3 4 5 #Swapped 4 and 0
#Swapping 7 times was the fewest swaps possible.
Winning Criterion
This is a code-golf
challenge. The fewest bytes of source code wins.
1
rather than0
as our minimum input value? \$\endgroup\$