Learn
Exam

Absolute Value Sorting

Difficulty
BEGINNER

Problem

Given an array of integers numbers, write a function solution that returns the array sorted in ascending order based on the absolute values of its elements. If two elements have the same absolute value, their original order is preserved after sorting. (Refer to Explanation for Test Case 1)


Constraints

  • The length of numbers is between 2 and 50 inclusive.
  • Each element in numbers is an integer between -100 and 100 inclusive.
  • numbers does not contain duplicate elements.

Test Case

Test Case Number numbers return
1 [-5,4,0,-4,5] [0,4,-4,-5,5]
2 [-10,7,-4,2,-9] [2,-4,7,-9,-10]
3 [-99,50,-75,25] [25,50,-75,-99]

Explanation for Test Case 1

  • When numbers=[-5,4,0,-4,5], sorting based on absolute values in ascending order results in [0,4,-4,-5,5].
  • 4 and -4 have the same absolute value, so their original order is preserved with 4 appearing before -4.
  • -5 and 5 have the same absolute value, so their original order is preserved with -5 appearing before 5.

Explanation for Test Case 2

  • When numbers=[-10,7,-4,2,-9], sorting based on absolute values in ascending order results in [2,-4,7,-9,-10].

Explanation for Test Case 3

  • When numbers=[-99,50,-75,25], sorting based on absolute values in ascending order results in [25,50,-75,-99].