Given an array of integers, sort it by pairs. Split the array into consecutive pairs starting from the first element, (nums[0], nums[1]), (nums[2], nums[3]), and so on, and put the two numbers of every pair in ascending order. Pairs never move relative to one another, and no number moves from one pair into another.
If the array has an odd length, the last number has no partner and stays where it is.
Function Signature
def sort_pairs(nums: list[int]) -> list[int]:
Rules
-
For every even index
i
with
i + 1 < len(nums)
, the output holds the smaller of
nums[i]
and
nums[i + 1]
at index
i
and the larger at index
i + 1
.
-
If
len(nums)
is odd, the last element of the output equals the last element of
nums
.
-
A pair of equal values is left as it is.
-
Return a list of the same length as
nums
. You may reorder
nums
in place and return it, or return a new list.
Constraints
-
1 <= len(nums) <= 10^5
-
-10^9 <= nums[i] <= 10^9
Examples
Example 1
Input: nums = [5, 4, 2, 3, 7]
Output: [4, 5, 2, 3, 7]
The pair (5, 4) becomes (4, 5), the pair (2, 3) is already in order, and 7 has no partner, so it does not move.
Example 2
Input: nums = [9, 1, 8, 2]
Output: [1, 9, 2, 8]
Each pair is sorted on its own. The result as a whole is not sorted, and it should not be.
Example 3
Input: nums = [6]
Output: [6]