JS Basic algorithm: Bubble sort, two-point lookup

Source: Internet
Author: User

Knowledge Expansion:

Time complexity: The time complexity of the algorithm is a function that describes the running time of the algorithm. The lower the complexity of time, the higher the efficiency.

Self-understanding: An algorithm, run a few times the complexity of how much, such as running n times, the time complexity of O (n).

1. Bubble sort

Resolution: 1. Compare adjacent two elements if the previous one is larger than the next, then swap the position.

2. The last element in the first round should be the largest one.

3. Follow the method of step one to compare the adjacent two elements, this time because the last element is already the largest, so the last element is not compared.

   

1 functionsort (elements) {2   for(vari=0;i<elements.length-1;i++){3    for(varj=0;j<elements.length-i-1;j++){4    if(elements[j]>elements[j+1]){5     varswap=Elements[j];6Elements[j]=elements[j+1];7elements[j+1]=swap;8    }9   }Ten  } One } A   - varelements = [3, 1, 5, 7, 2, 4, 9, 6, 10, 8]; -Console.log (' Before: ' +elements); the sort (elements); -Console.log (' after: ' + elements);

2. Two points Search

Parsing: Two-point lookup, also for binary lookup. First of all to find an intermediate value, by comparing with the median, big put and small on the left. Then look for the middle value on both sides, and continue above until you find your location.

1 functionbinary (data,item,start,end) {2     varEnd=end | | Data.length-1;3     varStart=start | | 0;4     varM=math.floor ((start+end)/2);5     if(item==Data[m]) {6         returnm;7}Else if(item<Data[m]) {8         returnBinary (data,item,start,m-1)//Recursive call9}Else{Ten         returnBinary (data,item,m+1, end); One     } A     return false; - } -  the     vararr=[34,12,5,123,2,745,32,4]; -  -Binary (arr,5);

JS Basic algorithm: Bubble sort, two-point lookup

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.