Advertisement
satishfrontenddev5

Untitled

Jan 6th, 2024 (edited)
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Given an array of integers, sort the array based on the absolute value of the elements.
  3.  
  4. Input format
  5. First line contains an integer n - The number of elements.
  6.  
  7. Second line contains n space separated integers - The array nums.
  8.  
  9. Output format
  10. For each test case print the minimum changes required on a separate line.
  11.  
  12. Sample Input 1
  13. 5
  14.  
  15. 2 -5 1 -2 4
  16.  
  17. Sample Output 1
  18. 1 2 -2 4 -5
  19.  
  20. Explanation 1
  21. Absolute values of elements are [2,5,1,2,4] respectively, so in the sorted order based on absolute values elements will be [1,2,-2,4,-5] or [1,-2,2,4,-5]. Both are accepted answers.
  22.  
  23. Constraints
  24. 1 <= n <= 10^5
  25.  
  26. -10^9 <= nums[i] <= 10^9
  27. */
  28.  
  29. function absoluteFuntion(n){
  30.     return Math.abs(n);
  31. }
  32.  
  33. /**
  34.  * @param {number} n
  35.  * @param {number[]} nums
  36.  * @return {number[]}
  37.  */
  38. function sortArrayAbsolute(n, nums) {
  39.     nums.sort((a,b)=>{
  40.         return absoluteFuntion(a)-absoluteFuntion(b);
  41.     })
  42.     return nums;
  43. }
  44.  
  45. function main() {
  46.     const n = parseInt(readLine(), 10)
  47.     const nums = readIntArr()
  48.     const result = sortArrayAbsolute(n, nums)
  49.     console.log(result.join(" "))
  50. }
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement