Answers for "javascript insertion sort"

3

insertion sort javascript

let insertionSort = (inputArr) => {
    for (let i = 1; i < inputArr.length; i++) {
        let key = inputArr[i];
        let j = i - 1;
        while (j >= 0 && inputArr[j] > key) {
            inputArr[j + 1] = inputArr[j];
            j = j - 1;
        }
        inputArr[j + 1] = key;
    }
    return inputArr;
};
Posted by: Guest on September-04-2020
1

Insertion Sort javascript

const insertionSort = (inputArr) => {
  const {length} = inputArr;
  const retArray = inputArr;
  for (let i = 1; i < length; i++) {
    const key = inputArr[i];
    let j = i - 1;
    while (j >= 0 && inputArr[j] > key) {
      retArray[j + 1] = inputArr[j];
      j -= 1;
    }
    retArray[j + 1] = key;
  }
  return retArray;
};
insertionSort([10, 9, 8, 7, 6, 5, 4, 3, 2, 1])
Posted by: Guest on November-11-2020
0

array sorting javascript insertion sort

function insertionSort(inputArr) {
    let n = inputArr.length;
        for (let i = 1; i < n; i++) {
            // Choosing the first element in our unsorted subarray
            let current = inputArr[i];
            // The last element of our sorted subarray
            let j = i-1; 
            while ((j > -1) && (current < inputArr[j])) {
                inputArr[j+1] = inputArr[j];
                j--;
            }
            inputArr[j+1] = current;
        }
    return inputArr;
}
Posted by: Guest on September-04-2020
1

javascript insertion sort

const insertionSort = array => {
  const arr = Array.from(array); // avoid side effects
  for (let i = 1; i < arr.length; i++) {
    for (let j = i; j > 0 && arr[j] < arr[j - 1]; j--) {
      [arr[j], arr[j - 1]] = [arr[j - 1], arr[j]];
    }
  }
  return arr;
};

console.log(insertionSort([4, 9, 2, 1, 5]));
Posted by: Guest on March-29-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language