JS Sort bubble Sort, select sort, insert sort

Source: Internet
Author: User

Bubble Sort :

The data in the array, in turn, compares the size of the adjacent two numbers.

If the previous data is larger than the subsequent data, the two numbers are exchanged.

Time complexity O (n^2)
1 functionBubble (array) {2     vartemp;3      for(vari=0; i<arr.length; i++){4          for(varj=0; j<arr.length; J + +){5             if(arr[j]>arr[j+1]){6temp = arr[j+1];7ARR[J+1] =Arr[j];8arr[j]=temp;9             }Ten }console.log (arr); One     } A}//Bubble Sort

Select Sort:

First select a minimum data from the original array, and the first position 1 data exchange.

Then select the minor data from the remaining n-1 data and exchange it with the second position data.

Repeat and know the last two data to complete the exchange.

Time complexity O (n^2)
functionSelectionsort (array) {varmin,temp;  for(vari=0; i<array.length-1; i++) {min=i;  for(varj=i+1; j<array.length; J + +){            if(array[j]<Array[min]) {min=J;                }} swap (array,min,i); } console.log (array);}//Select SortfunctionSwap (array,i,j) {vartemp =Array[i]; Array[i]=Array[j]; ARRAY[J]=temp;}//Two digital Exchange

Insert Sort:

First two data were compared from small to large.

The third data is then compared with the top two rows, and the third data is inserted into the appropriate position. And so on

(Insert sort has two loops, outer loop moves the array one by one, the inner loop compares the elements of the outer loop and the number preceding him.) )

Time complexity O (n^2)

1 functionInsertsort (arr) {2     vartemp, J;3      for(varI=1; i<arr.length; i++){4temp =Arr[i];5j=i;6          while(J>0 && arr[j-1]>temp) {7Arr[j]=arr[j-1];8j--;9         }Tenarr[j]=temp; One  A     } -          -}

JS Sort bubble Sort, select sort, insert sort

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.