Last active
January 20, 2016 17:08
-
-
Save jtribble/29e35090895ab654e5d7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// | |
// See: http://careercup.com/question?id=5201559730257920 | |
// | |
// Given an array which has positive and negative ints, sort | |
// the list so that all positives come after negatives, and the | |
// relative order is preserved. | |
// | |
// Input: [-1, 2, 2, -2, -3, 1, 10, 9, -9] | |
// Output: [-1, -2, -3, -9, 2, 2, 1, 10, 9] | |
// | |
/** | |
* @param {array} list - The array to modify | |
* @return {array} - The modified array | |
*/ | |
const sortNegsFirst = list => { | |
for (let i = 0; i < list.length; i++) { | |
if (list[i] > 0) { | |
let j = i + 1; | |
do { | |
if (list[j] < 0) { | |
moveNeg(list, j); | |
break; | |
} | |
j++; | |
} while (list[j] !== undefined); | |
} | |
} | |
return list; | |
}; | |
/** | |
* Move negative item before all positive items | |
* | |
* @param {array} list - The array to modify | |
* @param {number} i - The index of the negative item | |
*/ | |
const moveNeg = (list, i) => { | |
let ri = i; | |
let li = i - 1; | |
while (list[li] !== undefined && list[li] > 0) { | |
let temp = list[li]; | |
list[li] = list[ri]; | |
list[ri] = temp; | |
li--; | |
ri--; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment