insertion sort j code example

Example 1: java insertion sort

/**
* Insertion sort algorithm, O(n^2) time complexity.
*/
public static void insertionSort(int[] arr) {
  int n = arr.length;
  for(int i = 1; i < n; i++) {
    int key = arr[i];
    int j = i - 1;
    //shift until you find the position to place the element 'key'
    while(j >= 0 && arr[j] > key) {
      arr[j+1] = arr[j];
      j--;
    }
    //place element 'key' in the correct position in the sorted part of the array
    arr[j+1] = key;
  }
}

Example 2: insertion sort js

let insertionSort = (inputArr) => {    let length = inputArr.length;    for (let i = 1; i < 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;};