Three implementations of bubble sort

Source: Internet
Author: User

Bubble sort idea is easy to understand: Compare the array of two adjacent data, if the previous data is larger than the subsequent data, the two data is exchanged, each cycle, the largest data will be transferred to the last.

Algorithm One implementation:

#include <stdio.h>voidSwap (int&a,int&b) {a= a ^b; b= a ^b; A= a ^b;}intMain () {intA[] = {9,6,8,7,4,5,Ten,1,2,3} ;  for(inti =9; i >0; i--)         for(intj =0; J < I; J + +)             if(A[j] > a[j+1]) Swap (a[j],a[j+1]) ;  for(inti =0; I <Ten; i++) printf ("%d", A[i]); printf ("\ n") ; return 0 ;}

Algorithm two implementation (reduce the number of cycle judgment):

#include <stdio.h>voidSwap (int&a,int&b) {a= a ^b; b= a ^b; A= a ^b;}intMain () {intA[] = {9,6,3,8,5,2,7,4,1} ; BOOLFlag =true ;  for(inti =8; i >0&& flag = =true; i--)    {         for(intj =0, flag =false; J < I; J + +)    {            if(A[j] > a[j+1]) {Swap (a[j],a[j+1]) ; Flag=true ; }        }    }     for(inti =0; I <9; i++) printf ("%d", A[i]); printf ("\ n") ; return 0 ;}

Algorithm three implementations (reduce the number of cycle judgments):

#include <stdio.h>voidSwap (int&a,int&b) {a= a ^b; b= a ^b; A= a ^b;}intMain () {intA[] = {9,6,3,8,5,2,7,4,1} ; intLen =8 ;  while(Len >0)    {        inti =Len;  for(intj =0; J < I; J + +)    {            if(A[j] > a[j+1]) {Swap (a[j],a[j+1]) ; Len=J; }        }    }     for(inti =0; I <9; i++) printf ("%d", A[i]); printf ("\ n") ; return 0 ;}

Three implementations of 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.