Exchange two data in an algorithm

Source: Internet
Author: User

The server is a little bit dull these two days. (⊙o⊙) (⊙o⊙)

Here you can use the bubble sort demo to illustrate.

The first of the most low one with the help of the middle variable line 5 6 7

1     functionBubble (arr) {2          for(vari = 0, length = arr.length; i < length; i++) {3              for(varj = 0; J < length-1-I.; J + +) {4                 if(Arr[j] > arr[j+1]) {5                     vartemp =Arr[j];6ARR[J] = arr[j+1];7ARR[J+1] =temp;8                 }9             }Ten         } One         returnarr; A}

The second type does not use the middle variable line 5 6 7

1 functionBubble (arr) {2      for(vari = 0, length = arr.length; i < length; i++) {3          for(varj = 0; J < length-1-I.; J + +) {4             if(Arr[j] > arr[j+1]) {5ARR[J] = Arr[j] + arr[j+1];6ARR[J+1] = arr[j]-arr[j+1];7ARR[J] = arr[j]-arr[j+1];8             }9         }Ten     } One     returnarr; A}

The third recommended line 5 with the help of arrays

1 functionBubble (arr) {2      for(vari = 0, length = arr.length; i < length; i++) {3          for(varj = 0; J < length-1-I.; J + +) {4             if(Arr[j] > arr[j+1]) {5ARR[J] = [arr[j+1], arr[j+1] = arr[j]][0];6             }7         }8     }9     returnarr;Ten}

Knowledge to a little accumulation of summary, to Daniel worship at the same time, but also to walk oh. Master the Good Foundation, think more, summarize more.

Dear You happy Mid-Autumn Festival!

Exchange two data in an algorithm

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.