Bubble sort Java Code

Source: Internet
Author: User

The bubble sort is to take the maximum number out in turn, and then swap to the last edge of the array.

Intuitive notation:

 Public Long[] Sort (Long[] a) {                intn = a.length-1; //Step:1 Select the maximum number         for(inti = 0; I < n; i++){            //swap If the previous number is greater than the last number            if(A[i] > a[i+1]) {A[i]= A[i] ^ a[i+1]; A[i+1] = a[i+1] ^A[i]; A[i]= A[i] ^ a[i+1]; }} N--; //Step:2 to elect the second largest number         for(inti = 0; I < n; i++){            //swap If the previous number is greater than the last number            if(A[i] > a[i+1]) {A[i]= A[i] ^ a[i+1]; A[i+1] = a[i+1] ^A[i]; A[i]= A[i] ^ a[i+1]; }} N--; //Step:3         for(inti = 0; I < n; i++){            //swap If the previous number is greater than the last number            if(A[i] > a[i+1]) {A[i]= A[i] ^ a[i+1]; A[i+1] = a[i+1] ^A[i]; A[i]= A[i] ^ a[i+1]; }} N--; //Step:4         for(inti = 0; I < n; i++){            //swap If the previous number is greater than the last number            if(A[i] > a[i+1]) {A[i]= A[i] ^ a[i+1]; A[i+1] = a[i+1] ^A[i]; A[i]= A[i] ^ a[i+1]; }} N--; System.out.println ("N=" +N); //Step:5         for(inti = 0; I < n; i++){            //swap If the previous number is greater than the last number            if(A[i] > a[i+1]) {A[i]= A[i] ^ a[i+1]; A[i+1] = a[i+1] ^A[i]; A[i]= A[i] ^ a[i+1]; }} N--; returnA; }

Add a For loop:

 Public Long[] Sort (Long[] a) {                intn = a.length-1;  for(intj = 0; J < A.length; J + +){             for(inti = 0; I < n; i++){                //swap If the previous number is greater than the last number                if(A[i] > a[i+1]) {A[i]= A[i] ^ a[i+1]; A[i+1] = a[i+1] ^A[i]; A[i]= A[i] ^ a[i+1]; }} N--; }        returnA; }

Bubble sort Java Code

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.