Sort algorithm (i) bubble sort

Source: Internet
Author: User

I used to learn C, recently learned Java, feel good.

Next year's graduate student, now I want to review the data structure, is the basic thing.

Let's start with the sorting algorithm. First bubble sort.

 Public classBubblesort { Public Static voidSortint[] a)//a simple bubbling algorithm.     {        //Static static can only be called statically        inttemp=0; intswapsteps=0;//Number of exchanges        intcomparesteps=0;//Number of comparisons        intflag=1;//If it is lined up, then the cycle will be useless, how to do? -You can set a flag and skip loops without swapping.          for(intI=0; i<a.length-1&&flag==1; i++) {flag=0;  for(intj=0; j<a.length-i-1; j + +) {comparesteps++; if(a[j]>a[j+1]) {temp=A[j]; A[J]=a[j+1]; A[j+1]=temp; Flag=1; Swapsteps++; }            }                             for(intk=0; k<a.length;k++) System. out. Print (a[k]+" "); System. out. println ('.'); } System. out. println ("It's a total comparison."+comparesteps+"Times"); System. out. println ("altogether exchanged."+swapsteps+"Times"); }     Public Static voidMain (string[] args) {int[] a={1,5,6,9,8,7,3,2,4,Ten};//why [] write in front, and C language is not the same ah?System. out. println ("the number of array members is:"+a.length+"a");    Sort (a); }}


Each time you go, a row is displayed.

The best n-1, the worst (n-1) n/2.

Sort algorithm (i) bubble sort

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.