Insert and sort insertion_sort JS implementation

Source: Internet
Author: User

Generally,Insert sortAll are implemented on the array using in-place. DetailsAlgorithmDescription:

    1. Starting from the first element, this element can be considered to have been sorted
    2. Extracts the next element and scans it forward from the back in the sorted element sequence.
    3. If the element (sorted) is greater than the new element, move the element to the next position.
    4. Repeat Step 3 until you find the position where the sorted elements are smaller than or equal to the new elements.
    5. Insert new elements to this position
    6. 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 }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.