Created
December 30, 2022 20:05
-
-
Save DeoluA/f72b547919f85c9542ab71d461bc072c to your computer and use it in GitHub Desktop.
Sort an array of integers in O(n) time. Array can also contain negative integers.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
/** | |
* @param raw_numbers: an array of integer values. Can either be positive or negative | |
* @return: sorted array, from negative to positive | |
*/ | |
const sortArrayOfIntegers = (raw_numbers) => { | |
let positives = {}, negatives = {}; | |
for(let m = 0; m < raw_numbers.length; m++) { | |
if(raw_numbers[m] >= 0) { | |
// has it occured before? | |
if(positives[raw_numbers[m]]) { | |
positives[raw_numbers[m]].push(raw_numbers[m]); | |
} | |
else positives[raw_numbers[m]] = [raw_numbers[m]]; | |
} | |
// if array contains only positives, comment out the following else bracket | |
else { | |
// has it occured before? | |
if(negatives[-1*raw_numbers[m]]) { | |
negatives[-1*raw_numbers[m]].push(raw_numbers[m]); | |
} | |
else negatives[-1*raw_numbers[m]] = [raw_numbers[m]]; | |
} | |
}; | |
let numbers = []; | |
// if array contains only positives, comment out the following four lines | |
numbers = [].concat.apply( | |
numbers, | |
Object.keys(negatives).reverse().map((eachNumber) => { return negatives[eachNumber] }) | |
); | |
numbers = [].concat.apply( | |
numbers, | |
Object.keys(positives).map((eachNumber) => { return positives[eachNumber] }) | |
); | |
return numbers; | |
} | |
console.log(sortArrayOfIntegers([-7,1,4,3,6,-13, -24, 0, 20, -1200])); // should return [-1200, -24, -13, -7, 0, 1, 3, 4, 6, 20] | |
console.log(sortArrayOfIntegers([-1,0,1,2,-1,-4])); // should return [-4, -1, -1, 0, 1, 2] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment