I. Basic Ideas
The basic concept of Bubble Sorting is to compare two adjacent elements in sequence, put a small number in front, and put a large number in the back.
That is, in the first sorting, first compare the numbers of 1st and 2nd, and put the decimal places before and after the big tree;
Then compare the numbers of 2nd and 3rd, and place the decimal places before and after the large numbers. And so on, continue until the last two digits are compared, before decimal places are placed, and after a large number is placed. So far, the first sorting is over, and the maximum number is placed at the end!
The second one: Compare from the first logarithm. Before placing the decimal number, after placing the big number, the comparison is always to the last 2nd (the last 1st is already the largest). The second one ends, returns a new maximum number at the last 2nd.
Repeat the preceding process until the sorting is completed.
Because the sorting process always places decimal places forward and large numbers backward, which is similar to bubble rising, it becomes a Bubble sorting.
Ii. Sample Code
public static void BubbleSort(int[] arr) { int n = arr.Length; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (arr[i] > arr[j]) { int temp; temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } }Iii. Efficiency Analysis
Stability
Space complexity O (1)
Time complexity O (n2)
Worst case: reverse order. N * (n-1)/two elements need to be exchanged.
Best case: Forward order, no need to swap element O (N)
If the initial status of the record sequence is "positive", the Bubble sorting process only needs to sort the sequence. During the sorting process, only n-1 exchanges are required, and no records are moved;
Otherwise, if the initial status of the record sequence is "backward", the record must be compared and moved N (n-1)/twice.
Therefore, the total time complexity of Bubble Sorting is O (n2 ).