java-Sorting algorithm-bubble sort

Source: Internet
Author: User

First, the principle of bubble sort

Bubble sort, that is, starting from the first element, through 22 exchange, so that the small first out, and then go to the second round to make the second small to come out, until the last round of the biggest out, sort of completed

Second, the bubble sort of pseudo-code implementation:

1 Bubblesort (A)2 {3     fori = 1To Length[a]4    {5         forj = Length[a] to i+16        {7            ifA[J] < A[j-1]8            {9Exchane A[j] and a[j-1];Ten            } One        } A    } -}

Third, the bubble sort Java source code implementation

ImportJava.util.Comparator; Public classBubblesort {/*** Define a generic bubble sort method * Learn how to use generics and how to implement bubble sort * Generic types cannot be of the underlying type (such as Int,double,char, etc.) and must be of a reference type (such as Integer, double, C Haracter)*/         Public Static<T>voidBubblesort (t[] T, comparator<?SuperT>comparator) {T temp= T[0];  for(inti = 0; i < t.length-1; i + +)        {             for(intj = t.length-1; J >= I+1; J--)                if(Comparator.compare (T[j-1], t[j]) > 0) {Temp= T[j-1]; T[j-1] =T[j]; T[J]=temp; }        }    }        /**     * @paramthe args * Main function is used for testing. */     Public Static voidMain (string[] args) {//TODO auto-generated Method StubInteger[] INTs = {2, 0, 5, 23, 1, 4, 8, 56, 19}; Bubblesort (INTs,NewComparator<integer> () {             Public intCompare (integer O1, integer o2) {returnO1.intvalue ()-O2.intvalue ();        }        });  for(inti:ints) {System.out.print (i+ " ");    } System.out.println (); }}

Operation Result:

Iv. Analysis of Complexity

O (n^2)

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.