Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const insertionSort = (arr) => {
- for (let i = 0; i < arr.length; i++) {
- let el = arr[i];
- let j;
- // loop over elements to the left of currentEl
- for (j = i - 1; j >= 0 && arr[j] > el; j--) {
- // keep inserting current element until it gets to its
- // proper place
- arr[j + 1] = arr[j];
- }
- // insert current element at the correct index
- arr[j + 1] = el;
- }
- return arr;
- }
- const foo = [5, 3, 1, 2, 4];
- insertionSort(foo); // returns [1, 2, 3, 4, 5]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement