| Copyright Notice: This article for Bo Master original article, without Bo Master permission not reproduced.
Bubble Sort:
Principle: bubble sort is repeated before and after the comparison of two data, the wrong order exchange, after each exchange, will move back a data, in the comparison. Until the pending sequence is repeated until no more swapping is needed, that is, the backlog sequence is sorted.
Complexity of Time:
(1). If the pending sequence is a positive order, then the ordered sequence needs only one scan, and if the number of elements in the sequence is n, then the time complexity is O (n). O (n) is the best time complexity.
(2). If the pending sequence is not a positive sequence, then the n-1 sequence is scanned for n-1 times for each scan. So the time complexity is O (N2).
Example: (in Q,h,c,y,p,a,m, for example, in ascending alphabetical order), see
Of course, above the sorting process of the first trip (the result of the first trip is: H,C,Q,P,A,M.Y), to the good order of the sequence, to go through the n-1 sequencing, the subsequent sorting process is the same as the first trip.
The bubble sort is to move the small element forward or the large element back. The comparison is an adjacent two element comparison, and the interchange also occurs between these two elements. Therefore, if the two elements are equal, it is not necessary, if the two equal elements are not adjacent, then even through the preceding 22 exchange two adjacent together, this time will not be exchanged, so the same elements of the order has not changed, so bubble sort is a stable sorting algorithm.
Basic knowledge of bubble sort (without source code)