Principle: Insert sort, also commonly known as direct insert sort. It is an efficient algorithm for sorting a small number of elements. Insertion sort is one of the simplest sorting methods. Its basic idea is to insert a record into an ordered list that has been sorted, thus creating a new ordered list that increases the number of records by one. In the process of its implementation, the use of a double-layer loop, the outer loop to all elements except the first element, the inner loop to the ordered list in front of the current element to be inserted position search, and move.

Illustration:

Code implementation:

Const insertSort = function (arr) {const insertSort = function (arr) {for (let I = 1; i < arr.length ; I ++) {// Data subscript I is the data to be inserted; Let currentNumber = arr[I] let insertIndex = i-1 // currentNumber = arr[I] let insertIndex = i-1 While (insertIndex >= 0 && arr[insertIndex] > currentNumber) {arr[insertIndex + 1] = arr[insertIndex] insertIndex-- } arr[insertIndex + 1] = currentNumber } return arr } const s = [22, 8 ,16 ,5 , 47, 1, 10, 3 , 15] console.log(insertSort(s))Copy the code