sorting via exchange of 2 elements
Description:
This Kata is based on Kata "Simple Fun #148: Exchange Sort(myjinxin2015)", but this time the input sequence is not restricted to 3 different elements, only.
Task
Sorting is one of the most basic computational devices used in Computer Science.
Given a sequence (length ≤ 5000) of values (duplicates allowed), your task is to find the minimum number of exchange operations necessary to make the sequence sorted.
One operation is the switching of 2 key values in the sequence.
Example
For sequence = ["A", "A", "B", "B", "C"], the result should be 0.
It's already a sorted sequence.
For sequence = [9, -2, 1, 1, 9, -2], the result should be 1.
We can switching sequence[0] and sequence[5].
For sequence = [1, 2, 3, 0], the result should be 3.
We can:
[1, 2, 3, 0]
switching sequence[0] and sequence[3]
--> [0, 2, 3, 1]
switching sequence[1] and sequence[3]
--> [0, 1, 3, 2]
switching sequence[2] and sequence[3]
--> [0, 1, 2, 3]
For sequence = [8, 8, 3, 9, 9, 9, 8, 9, 3], the result should be 4.
We can:
[8, 8, 3, 9, 9, 9, 8, 9, 3]
switching sequence[0] and sequence[3]
--> [9, 8, 3, 8, 9, 9, 8, 9, 3]
switching sequence[0] and sequence[8]
--> [3, 8, 3, 8, 9, 9, 8, 9, 9]
switching sequence[1] and sequence[2]
--> [3, 3, 8, 8, 9, 9, 8, 9, 9]
switching sequence[5] and sequence[7]
--> [3, 3, 8, 8, 8, 9, 9, 9, 9]
So 4 is the minimum number of operations for the sequence to become sorted.
Input/Output
[input] array sequence
The Sequence.
[output] an integer
the minimum number of operations needed to completly sort the input sequence.
Similar Kata:
Stats:
Created | May 17, 2021 |
Published | May 18, 2021 |
Warriors Trained | 33 |
Total Skips | 0 |
Total Code Submissions | 109 |
Total Times Completed | 7 |
Python Completions | 7 |
Total Stars | 2 |
% of votes with a positive feedback rating | 0% of 2 |
Total "Very Satisfied" Votes | 0 |
Total "Somewhat Satisfied" Votes | 0 |
Total "Not Satisfied" Votes | 2 |
Total Rank Assessments | 2 |
Average Assessed Rank | 5 kyu |
Highest Assessed Rank | 4 kyu |
Lowest Assessed Rank | 5 kyu |