Java sorting algorithm--bubble sort

Source: Internet
Author: User
Tags array length

Bubble sort (Bubble sort) is a simple sort algorithm. Each time the adjacent two numbers are compared, they are exchanged if their positions do not match.

Each comparison, the number of comparisons will be reduced one time, because the previous is better.

For example:

First time, compare 8 and 9, because 9 is greater than 8, so swap their positions

The first time second, compare 8 and 7, because 8 is greater than 7, so their position is unchanged

The first time third, compare 7 and 1, because 7 is greater than 1, so their position is unchanged

The first time fourth times, compare 1 and 5, because 5 is greater than 1, so swap their positions

The first time fifth times, compare 1 and 2, because 2 is greater than 1, so swap their positions

The following comparisons are similar

Key Code Snippet:

1  Public Static voidMain (string[] args) {2         3         int[] score = {8, 9, 7, 1, 5, 2};4         5          for(inti = 0; i < score.length-1; i++){6              for(intj = 0;j < score.length-1-I; J + +){7                 if(Score[j] < Score[j + 1]){8                     intTMP =Score[j];9SCORE[J] = score[j + 1];TenScore[j + 1] =tmp; One                 } A             } -         } -}

Memory bubble sort just need to remember a formula: Outer loop Array Length-1, inner loop array length -1-i

Java sorting 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.