Absolute Value Sort #121
Replies: 5 comments
-
#85 Hints We can try either a selection sort, or leveraging the sort function in the language library. |
Beta Was this translation helpful? Give feedback.
-
Approach:Approach #1: Selection Sort Write a custom comparison function, such as smaller(a, b) which is true if and only if a is supposed to come before b (and a != b). From here, we can repeatedly find the ‘smallest’ number in A[i], A[i+1], ..., A[A.length - 1] and swapping it with A[i]. |
Beta Was this translation helpful? Give feedback.
-
`function absSort(arr):
|
Beta Was this translation helpful? Give feedback.
-
Space Complexity: O(1), the additional space used by best.` |
Beta Was this translation helpful? Give feedback.
-
Approach #2: Custom Sort Leverage the sort function of your languages library. Usually, it will have support for either a custom comparison function. For a custom comparison function compare(a, b), typically we want to return -1 if a < b, 1 if a > b, and 0 if a == b. `function absSort(arr):
|
Beta Was this translation helpful? Give feedback.
-
Given an array of integers arr, write a function absSort(arr), that sorts the array according to the absolute values of the numbers in arr. If two numbers have the same absolute value, sort them according to sign, where the negative numbers come before the positive numbers.
Examples:
input: arr = [2, -7, -2, -2, 0]
output: [0, -2, -2, 2, -7]
Constraints:
[time limit] 5000ms
[input] array.integer arr
0 ≤ arr.length ≤ 10
[output] array.integer
Beta Was this translation helpful? Give feedback.
All reactions