C speech bubbling sorting algorithm and code
Fundamental ideas and examples
The basic idea of bubble sorting is to compare two adjacent numbers from time to time, so that the larger elements move back from time to time. After one round of comparison, the largest number is selected; after the second round of comparison, the second largest number is selected, and so on.
The following is illustrated by the sort of 3 2 4 1 stop bubbling.
The first round of sorting process
3 2 4 1 (finally)
2 3 4 2 (compare 3 and 2, AC)
2 3 4 1 (compared with 3 and 4, no communication)
2 3 1 4 (compared with 4 and 1, AC)
At the end of the first round, the maximum number of 4 was on the first side, so the second round of sorting only needs to be compared with the next three numbers.
The second round of sorting process
2 3 1 4 (consequences of the first round)
2 3 1 4 (analogous to 2 and 3, no communication)
2 1 3 4 (comparable to 3 and 1, AC
At the end of the second round, the second largest number was once ranked second to last, so the third round only needed to compare the first two elements.
The third round of sorting process
2 1 3 4 (consequences of the second round of sorting)
1 2 3 4 (comparable to 2 and 1, AC)
At this point, the sorting is complete.
Summary and completion of the algorithm
With regard to the array R [n] with N elements, stop a maximum of 1 round comparison of NMQ.
In the first round, compare one by one (R [1], R [2]), (R [2], R [3]), (R [3], R [4]), …... . (r [N-1], R [N]); the largest element is moved to R [N].
In the second round, compare one by one (R [1], R [2]), (R [2], R [3]), (R [3], R [4]), …... . (r [N-2], R [N-1]); the second largest element will be moved to R [N-1].
.
And so on, until all the arrays are sorted from small to large.
The general completion and optimization completion of bubble sorting are given below. Ordinary completion is a rare method in textbooks. No matter whether the array is sorted or not, the city will stop NMUI one round of comparison, while when the array has been sorted, the comparison will be added in advance, thus reducing the complexity of the algorithm.
Plain text copy # include # include # define N 8 void bubble_sort (int a [], int n); / / ordinary completion void bubble_sort (int a [], int n) / / n is the number of elements of the array a {/ / must stop NMel 1 round analogy for (int item0; I)