"JavaScript algorithm"---insert sort

Source: Internet
Author: User

First, what is called the insertion sorting method

There is an ordered sequence of data that requires a number to be inserted into the sorted data sequence, but the data sequence is still ordered after insertion, and a new sorting method is used-the insertion sort method

Second, the core

the basic operation of inserting a sort is to insert a data into the ordered data that is already sorted, so as to get a new sequential data with a number plus one, the algorithm is suitable for the ordering of a small amount of data. The insertion algorithm divides the array to be sorted into two parts: the first part contains all the elements of the array, except for the last element (where an array has more space to insert), and the second part contains only that element (that is, the element to be inserted). After the first part is sorted, the last element is inserted into the first part of the sequence. the principle of insertion sorting is very well understood and can be analogous to the selection of sorts. Selecting sort is done in two spaces, which means that each time you choose the most value from the old space to place the new space, and the insertion sort is done in the same spacethird, the ideastarting with the second digit, each number tries to compare and swap with the previous one and repeat the action. Stop until the previous number is absent or smaller or equal                                                                          

Four, the code

vararr = [19,3,22,7,55,9,3,8]vartemp; for(vari=1;i<arr.length;i++){    varindex =i;  while(index-1>=0 && arr[index-1] >Arr[index]) {[Arr[index],arr[index-1]] = [arr[index-1],arr[index]] Index--    }} for(vari=1;i<arr.length;i++){    varindex =i;  while(index-1>=0 && arr[index-1] >Arr[index]) {Temp=Arr[index]; Arr[index]= Arr[index-1]; Arr[index-1] =temp; Index--    }}

"JavaScript algorithm"---insert sort

Related Article

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.