Summary of common sorting Algorithms (Java edition)

Source: Internet
Author: User

First, bubble sort

1, principle: Adjacent elements 22 comparison, large back put. The first time is over, the maximum value is at the maximum index.

2. Code:

 Public Static voidBubblesort (int[] arr) {                     for(intx=0; x<arr.length-1; X + +) {//the outer loop control wheel number, altogether to compare (arr.length-1) Wheel                         for(inty=0; y<arr.length-1-x; y++) {//the outer loop controls the number of comparisons per round, each round comparing (arr.length-1-i) times                            if(Arr[y] > Arr[y+1]) {//if the preceding element is larger than the following element, the swap position                                inttemp =Arr[y]; Arr[y]= Arr[y+1]; Arr[y+1] =temp; }                        }                    }                }
View Code

Second, choose the sort

1, principle: The 0 position of the elements in turn and all the elements behind, compared to the end, 0 position is the smallest element, and then from the 1 position on the back of the element ratio, gradually get from small to large values.

2. Code:

 Public classSelectionsort { Public Static voidMain (string[] args) {int[] arr = {2, 5, 8, 3, 6};    Selectionsort (arr); }     Public Static voidSelectionsort (int[] arr) {         for(inti=0;i<arr.length;i++) {//The outer loop controls which position the number is compared to the number in the back             for(intj=i+1;j<arr.length;j++) {//the inner loop controls how many times this number needs to be compared to the subsequent number.                if(Arr[i]>arr[j]) {// //This condition is guaranteed to be arranged from small to large, and vice versa from large to small                    inttemp =Arr[i]; Arr[i]=Arr[j]; ARR[J]=temp; }            }        }                 for(intm=0;m<arr.length;m++) {System.out.println (arr[m]); }    }}
View Code

Summary of common sorting Algorithms (Java edition)

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.