Java Basic Learning Summary Five (recursive algorithm, bubble sort)

Source: Internet
Author: User

One: Recursive algorithm

Concept: Call your own method

The sample code is as follows:

1 @Test2     /**3 * Recursive summation4 * 5+4+3+2+1=155      */6      Public voidgetsum () {7         Longsum = SUM (5);8System.out.println ("sum=" +sum);9     }Ten  One      Public Static LongSuminti) { A         if(1 = =i) { -             return1; -}Else { the             returni + SUM (i-1); -         } -}

Explain:

When I=5, return to 5+sum (4),

When i=4, return to 4+sum (3),

When I=3, return to 3+sum (2),

When i=2, return to 2+sum (1),

When I=1, returns 1

Finally, the 5+4+3+2+1=15 is obtained;

Two: Bubble sort

Concept: If there are several numbers, 12, 23, 4, 3, 14

First: Take 12 compared with other numbers, if 12 is smaller than the other number, then swap position, which is descending order.

Original order: 12, 23, 4, 3, 14

After the first comparison: 23,12,4,3,14

Get a maximum value, on the leftmost side, in the second and subsequent numbers to compare, the same way as before

23,14,4,3,12

23,14,12,3,4

23,14,12,4,3

The sample code is as follows:

1 @Test2     /**3 * Bubble Sort4      */5      Public voidPupplesort () {6         int[] arr = {12, 23, 4, 3, 14 };7          for(inti = 0; i < arr.length; i++) {8              for(intj = i + 1; J < Arr.length; J + +) {9                 if(Arr[i] <Arr[j]) {Ten                     intTMP =Arr[i]; OneArr[i] =Arr[j]; AARR[J] =tmp; -                 } -             } the         } - System.out.println (arrays.tostring (arr)); -}

Java Basic Learning Summary Five (recursive algorithm, bubble 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.