Problem
Given an array numbers consisting of integer arrays of length 2, write a function solution that returns the array sorted based on the following criteria:
- Sort by the first element of each array in ascending order.
- If the first elements are equal, sort by the absolute value of the second element in ascending order.
- If the absolute values of the second elements are also equal, maintain the original order.
Constraints
- The length of
numbersis between 2 and 20 inclusive. - Each element in
numbersis an integer array of length 2. Each integer is between -100 and 100 inclusive. numbersdoes not contain duplicate elements.
Test Case
| Test Case Number | numbers | return |
|---|---|---|
| 1 | [[3,4],[2,-5],[3,-1],[1,7]] | [[1,7],[2,-5],[3,-1],[3,4]] |
| 2 | [[-1,2],[-1,-3],[0,5],[0,-4]] | [[-1,2],[-1,-3],[0,-4],[0,5]] |
| 3 | [[5,-6],[3,2],[5,6],[2,1]] | [[2,1],[3,2],[5,-6],[5,6]] |
Explanation for Test Case 1
- When
numbers=[[3,4],[2,-5],[3,-1],[1,7]]:- Sort by the first element in ascending order: intermediate result is
[[1,7],[2,-5],[3,4],[3,-1]]. - For elements with the same first value
[3,4]and[3,-1], sort by the absolute value of the second element. - The final sorted result is
[[1,7],[2,-5],[3,-1],[3,4]].
- Sort by the first element in ascending order: intermediate result is
Explanation for Test Case 2
- When
numbers=[[-1,2],[-1,-3],[0,5],[0,-4]]:- Sort by the first element in ascending order: intermediate result is
[[-1,2],[-1,-3],[0,5],[0,-4]]. - For elements with the same first value
[-1,2]and[-1,-3], sort by the absolute value of the second element. - Also, sort elements
[0,5]and[0,-4]by the absolute value of the second element. - The final sorted result is
[[-1,2],[-1,-3],[0,-4],[0,5]].
- Sort by the first element in ascending order: intermediate result is
Explanation for Test Case 3
- When
numbers=[[5,-6],[3,2],[5,6],[2,1]]:- Sort by the first element in ascending order: intermediate result is
[[2,1],[3,2],[5,-6],[5,6]]. - For elements with the same first value
[5,-6]and[5,6], sort by the absolute value of the second element. - However, since the absolute values of the second elements are both
6, maintain the original order. - The final sorted result is
[[2,1],[3,2],[5,-6],[5,6]].
- Sort by the first element in ascending order: intermediate result is