Implementation of Java bubbling sequencing

Source: Internet
Author: User

Bubble sort idea: Compare the two adjacent elements to match the required exchange position.

In the example, the adjacent two elements are compared, the large put to the right, the final realization from small to large sort.

The first step: first implement the maximum value in an array at the far right:

 Public Static voidMain (String args[]) {int[] arr = {12,4,2,34,8};//defines an array of arrBubblesort (arr);//Call Method BubblesortSystem.out.println ("After sorting:");//Print the final result         for(inti = 0;i<arr.length;i++) {System.out.print (Arr[i]+","); }    }         Public Static voidBubblesort (int[] arr) {               for(inti = 0; i<arr.length-1;i++){            if(arr[i]>arr[i+1]){                inttemp =Arr[i]; Arr[i]= Arr[i+1]; Arr[i+1] =temp; }        }    }            

Print it as follows:

After sorting is:
4,2,12,8,34,

Step two: Send the second largest value to the left of the last one.

Add the following code snippet:

for (int  i = 0;i<arr.length-1-1;i++) {  if(arr[i]>arr[i+1]) {      int temp = arr[i];      = Arr[i+1];     Arr[i+1] = temp;         }   }

Similarly, one analogy, and finally the number from small to large sorting;

Summarize our code,

     Public Static voidMain (String args[]) {int[] arr = {8,34,4,2,12};            Bubblesort (arr); Definition method Bubblesort System.out.println ("After sorting:");  for(inti = 0;i<arr.length;i++) {System.out.print (Arr[i]+","); }    }     Public Static voidBubblesort (int[] arr) {         for(intj = 0;j<arr.length-1;j++{//j is used to control the number of wheels, as long as the length-1 wheel for(inti = 0;i<arr.length-1-j;i++) {I is used to control the comparison and switching between two numbersif(arr[i]>arr[i+1]){                    inttemp =Arr[i]; Arr[i]= Arr[i+1]; Arr[i+1] =temp; }            }        }    }

After sorting is:
2,4,8,12,34,

Implementation of Java bubbling sorting

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.