Skip to content

Instantly share code, notes, and snippets.

@malaquiasdev
Created May 3, 2022 23:55
Show Gist options
  • Save malaquiasdev/28101968560ac926ab303d4adcb948a1 to your computer and use it in GitHub Desktop.
Save malaquiasdev/28101968560ac926ab303d4adcb948a1 to your computer and use it in GitHub Desktop.
Sorted Squared Array
function sortedSquares(squares = []) {
const squaredArray = squares.map(square => square * square);
for (let i = 1; i < squaredArray.length; i++) {
const value = squaredArray[i];
let j = i - 1;
for(j; j >= 0 && squaredArray[j] > value; j--) {
squaredArray[j + 1] = squaredArray[j];
}
squaredArray[j+1] = value;
}
return squaredArray;
}
console.log('Test Case 1', sortedSquares([1, 2, 3, 5, 6, 8, 9]));
console.log('Test Case 2', sortedSquares([-2, -1]));
console.log('Test Case 3', sortedSquares([-10, -5, 0, 5, 10]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment