Skip to content

Instantly share code, notes, and snippets.

@kkchu791
Created February 24, 2019 20:43
Show Gist options
  • Save kkchu791/2ad383327294be8919715880f32aef8a to your computer and use it in GitHub Desktop.
Save kkchu791/2ad383327294be8919715880f32aef8a to your computer and use it in GitHub Desktop.
Using insertion sort
// Given an array of integers A sorted in non-decreasing order,
// return an array of the squares of each number, also in sorted non-decreasing order.
// array = [-4,-1,0,3,10]
const sortedSquares = (array) => {
// square the elements in the array
const squaredArray = array.map(el => el * el);
// use insertion sort to sort the array from min to max
// squaredArray = [16, 1, 0 , 9, 100]
for (let k = 1; k < squaredArray.length; k++) {
let key = squaredArray[k]
let j = k - 1
while (j >= 0 && squaredArray[j] > key) {
squaredArray[j+1] = squaredArray[j];
j--;
}
squaredArray[j+1] = key
}
return squaredArray;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment