Count the shifts
Standard · Write code · about 10 min
Return how many times insertion sort shifts a value one cell to the right while it sorts nums ascending. A key that stays where it is costs no shift.
Example 1
Input:
[[4,1,3,5,2]]
Output:
5
1 shifts 4; 3 shifts 4; 5 stays; 2 shifts 5, 4 and 3.
Example 2
Input:
[[1,2,3]]
Output:
0
Sorted input needs no shifts.
Constraints
- 0 ≤ nums.length ≤ 1,000
- -10,000 ≤ nums[i] ≤ 10,000
Learn the idea first: Insertion sort, a visual lesson.
More Insertion sort problems
- State after inserting the 4th element Warm-up
- Implement insertion sort Standard
- Spot the bug: the first cell Standard
- Insertion sort on a linked list Challenge