[Principle] It is a simple sorting algorithm. It traverses several secondary sorting columns, and each time it goes through, it will compare the size of two adjacent numbers from the past to the next; if the former is larger than the latter, it will switch their positions. In this way, after a traversal, the maximum element is at the end of the series. In the same way, the second largest element is arranged before the largest element. Repeat this operation until the entire sequence is ordered. [Complexity]
The time complexity of Bubble Sorting is O (n2), and the space complexity is O (n). It is a stable sorting algorithm.
Note that after each bubble round, the last number must be the maximum value after this round of sorting. The next round does not have to be involved in the bubble. So the upper limit of the internal loop is the size-i-1.
[Code]
# Include <iostream> using namespace STD; Template <class T> void bubble_sort (T array [], const int size) {T temp; // The intermediate variable int flag; // key code used to mark for (INT m = 0; m <size-1; m ++) // bubble sort, and determine the boundary of the External Loop (that is, the maximum value of the loop) {flag = 0; For (INT n = 0; n <size-1-m; n ++) {If (array [N]> array [n + 1]) // The internal loop is used to compare and exchange data {temp = array [N]; array [N] = array [n + 1]; array [n + 1] = temp; flag = 1; // If switching occurs, set it to 1} If (flag = 0) {break; // if no exchange occurs, the sequence is sorted }}int main () {int temp; // The intermediate variable int A [10]; cout <"Please input 10 numbers:" <Endl; for (INT I = 0; I <10; I ++) // enter the original array {CIN> A [I];} bubble_sort (A, sizeof () /sizeof (INT); For (Int J = 0; j <10; j ++) // output the sorted Array {cout <A [J] <"" ;}return 0 ;}