Java Bubble sort Algorithm code _java

Source: Internet
Author: User

Copy Code code as follows:



/**


* Principle:


* for n cycles, each cycle from the back forward to the adjacent two elements of the comparison, small forward, big back


 *


* Time Complexity:


* Average condition: O (n^2)


* Best case: O (n)


* Worst case: O (n^2)


 *


* Stability: Stable


 **/


public class bubble sort {

    public int[] Bubblesort (int[] A, int n) {
        for (int i = 0; I < n; i++) {
            int flag = 0;
            for (int j = n-1 J > I j--) {//I or i-1?
                if (A[j] < a[j-1]) {
                     int x = a[j];
                     A[j] = a[j-1];
                     a[j-1] = x;
                     flag = 1;
&NBsp;              }
            }
             if (flag = 0)
                 break;
       }
        return A;
   }

/**
* @param args
*/
public static void Main (string[] args) {
TODO auto-generated Method Stub
Int[] A = new int[] {25, 56, 32, 20, 1, 5, 89, 3, 8, 41};
Bubble sort sort = new bubble sort ();
Sort.bubblesort (A, a.length);
for (int i = 0; i < a.length; i++) {
System.out.print (A[i] + "");
}
}
}

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.