Bubble sort
What is bubble sort
If you usually have to watch the blister to pay who face the situation can be found that the blisters from the bottom up is gradually increasing, rising to the surface of the time is often the most blisters when, as shown.
The bubble sort principle is similar to this one, so that the largest elements in the subsequence are constantly sink to achieve the purpose of sorting. To put it bluntly, the bubbling sort is traversed by N-1, in which the first n-i elements (i+1 to n elements have been sorted), and the elements of the large I are moved to the n-i position.
The process of bubbling the sort can be described as follows:
So that a is an array of sorts, N represents the length of a, a[i] represents the i+1 element of array A, I=1,1,2,3...N
First traversal:
Starting from I=0, the first n elements are traversed, if a[i]>a[i+1], then the values of a[i] and a[i+1] are exchanged, and the maximum value of the top n elements will appear on the nth position in the initial traversal;
Second traversal:
Starting from I=0, the first N-1 element is traversed, if a[i]>a[i+1], then the value of A[i] and a[i+1] is exchanged, and the second traversal will have the largest value in the first N-1 element to appear in the first N-1 position;
......
Section N-1 Traversal:
The last traversal is the comparison of a[0] and a[1], if a[0]>a[1], the position of the two exchanges, the end of the sort; otherwise, the sort ends without swapping.
Bubbling Process Demo
An array of a={14,5,16,4,7,9} is ordered from small to large, and the bubbling sort process is as follows:
First traversal:
Second traversal:
Third traversal:
Last traversal:
C + + version code implementation
1#include"stdafx.h"2#include <iostream>3 using namespacestd;4 voidBubblesort (int*values,intlength) {5 inttemp=0;6 for(inti=length-1;i>0; i--){7 for(intj=0; j<i;j++){8 if(* (VALUES+J) >* (values+j+1)){9temp=* (values+j);Ten* (VALUES+J) =* (values+j+1); One* (values+j+1)=temp; A } - } - } the } - intMainintARGC, _tchar*argv[]) - { - intvalues[]={ -,5,8, -, -, One}; +Bubblesort (values,6); - for(intI=0;i<6; i++){ +cout<<* (values+i) <<Endl; A } at return 0; -}
Sort Series algorithm--bubble sort