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