Intermediate Level

Implement the sortArrayByAbsoluteValue method that returns the array sorted according to absolute value.

The input contains an integer array nums and its length size. Your task is to sort the array by absolute value in ascending order.

The absolute value ignores the sign of a number. If two numbers have the same absolute value, place the smaller actual number first. For example, [-3,3,-2] becomes [-2,-3,3].

Example 1

Input
nums (int[]) = [-5,2,-1,4]
size (int) = 4
Returns (int[]) [-1,2,4,-5]

Example 2

Input
nums (int[]) = [-3,3,-2]
size (int) = 3
Returns (int[]) [-2,-3,3]

Example 3

Input
nums (int[]) = [0,-1,1]
size (int) = 3
Returns (int[]) [0,-1,1]

Compare numbers using their absolute values instead of their original values.

Sort the array with a custom comparison rule. A number with a smaller absolute value comes first. If two numbers have the same absolute value, compare the actual numbers and put the smaller one first.

Pseudocode:

function sortArrayByAbsoluteValue(nums, size):
    sort nums using this rule:
        if abs(a) != abs(b):
            a comes before b when abs(a) < abs(b)
        else:
            a comes before b when a < b
    return nums
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.