Selection Sort Operation Counter
You are required to simulate an instrumented Selection Sort algorithm to count the exact number of key comparisons and swaps performed during the sorting process.
You must implement a class SelectionSortSimulator with a single method:
- simulate(arr): Takes a vector<int> by reference and sorts it in place using the Selection Sort algorithm. The method must return a vector<int> containing exactly two integers: [comparison_count, swap_count].
The algorithm must strictly follow this logic to ensure counts match exactly:
- Iterate an outer loop variable i from 0 through N - 2.
- Set minIndex = i.
- Iterate an inner loop variable j from i + 1 through N - 1.
- Count one key comparison every time the condition arr[j] < arr[minIndex] is evaluated.
- If the strict comparison is true, update minIndex = j.
- After the inner loop finishes, if minIndex differs from i, swap arr[i] and arr[minIndex] and count one swap.
Example 1:
Input: arr = [3, 1, 2]
Output: [3, 2]
Explanation:
- i=0: minIndex=0.
- j=1: 1 < 3 evaluates true (comparison 1). Update minIndex=1.
- j=2: 2 < 1 evaluates false (comparison 2).
- minIndex (1) differs from i (0). Swap 3 & 1 (swap 1). Array is now [1, 3, 2].
- i=1: minIndex=1.
- j=2: 2 < 3 evaluates true (comparison 3). Update minIndex=2.
- minIndex (2) differs from i (1). Swap 3 & 2 (swap 2). Array is now [1, 2, 3].
Total returned: 3 comparisons, 2 swaps.
Example 2:
Input: arr = []
Output: [0, 0]
Explanation:
- N=0. The array is empty.
- The outer loop condition i < N - 1 prevents any iterations.
Total returned: 0 comparisons, 0 swaps.
Now Your Turn!
Pick the correct output for the given inputInput: arr = [1, 2, 3]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 0 <= N <= 104
- -109 <= arr[i] <= 109
- Duplicates, already sorted input, and reverse-sorted input must all follow the exact same counting rules.
- If N=0 or N=1, the outer loop does not execute, resulting in 0 comparisons and 0 swaps.