Learn
Exam

Array Sorting

Difficulty
BEGINNER

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 numbers is between 2 and 20 inclusive.
  • Each element in numbers is an integer array of length 2. Each integer is between -100 and 100 inclusive.
  • numbers does 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]]:
    1. Sort by the first element in ascending order: intermediate result is [[1,7],[2,-5],[3,4],[3,-1]].
    2. For elements with the same first value [3,4] and [3,-1], sort by the absolute value of the second element.
    3. The final sorted result is [[1,7],[2,-5],[3,-1],[3,4]].

Explanation for Test Case 2

  • When numbers=[[-1,2],[-1,-3],[0,5],[0,-4]]:
    1. Sort by the first element in ascending order: intermediate result is [[-1,2],[-1,-3],[0,5],[0,-4]].
    2. For elements with the same first value [-1,2] and [-1,-3], sort by the absolute value of the second element.
    3. Also, sort elements [0,5] and [0,-4] by the absolute value of the second element.
    4. The final sorted result is [[-1,2],[-1,-3],[0,-4],[0,5]].

Explanation for Test Case 3

  • When numbers=[[5,-6],[3,2],[5,6],[2,1]]:
    1. Sort by the first element in ascending order: intermediate result is [[2,1],[3,2],[5,-6],[5,6]].
    2. For elements with the same first value [5,-6] and [5,6], sort by the absolute value of the second element.
    3. However, since the absolute values of the second elements are both 6, maintain the original order.
    4. The final sorted result is [[2,1],[3,2],[5,-6],[5,6]].