Quick actions

cmd+k|ctrl+k

Navigation

Languages

Insertion Sort

Snippet info

Language

JavaScript

Visibility

public

Author

anikeshdey2020

Created

2023-03-04T03:37:58.858125Z

Updated

2023-03-04T03:37:58.858125Z

function sort(array){
    const length = array.length;
	for (let i = 0; i < length; i++) {
		if (array[i] < array[0]) {
          //move number to the first position
          array.unshift(array.splice(i,1)[0]);
        } else {
          // only sort number smaller than number on the left of it. This is the part of insertion sort that makes it fast if the array is almost sorted.
          if (array[i] < array[i-1]) {
            //find where number should go
            for (var j = 1; j < i; j++) {
              if (array[i] >= array[j-1] && array[i] < array[j]) {
                //move number to the right spot
                array.splice(j,0,array.splice(i,1)[0]);
              }
            }
          }
        }
	}

    return array;
}


sort([2,6, 78, 86,34,56, 15, 90, 9, 25, 0, 64])
INFO