Generally,Insert sortAll are implemented on the array using in-place. DetailsAlgorithmDescription:
- Starting from the first element, this element can be considered to have been sorted
- Extracts the next element and scans it forward from the back in the sorted element sequence.
- If the element (sorted) is greater than the new element, move the element to the next position.
- Repeat Step 3 until you find the position where the sorted elements are smaller than or equal to the new elements.
- Insert new elements to this position
- Repeat the steps
Pseudo Code As follows:
Insertion - Sort ( A )
For J Bytes To Length [ A ]
Do Key Bytes A [ J ]
I Bytes J - 1
While I > 0 And A [ I ] < Key
Do A [ I + 1 ] Bytes A [ I ]
I Bytes I - 1
A [ I + 1 ] Bytes Key
JS implementation is as follows:
1 VaR Arr = [5, 2, 4, 6, 1, 3], key;
2 For ( VaR J = 1; j <arr. length; j ++ ){
3 // Debugger;
4 // Sort the order
5 VaR I = J-1;
6 Key = arr [J];
7 While (I> = 0 & arr [I]> key ){
8 Arr [I + 1] = arr [I];
9 I --;
10 }
11 Arr [I + 1] = key;
12 }