Bubble sorting is a kind of stable sorting, the average time complexity is O(n^2), the best time complexity is O(n), the worst is O(n^2).
During sorting, only the size of the current element and the next element are compared each time. If the current element is larger than the next element, it is exchanged. In this way, each round of sorting can ensure that the largest element under the current sorting is sent to the end of the unsorted part.
There are n elements to be arranged, so the overall large arrangement of n-th array should be executed.
The size of the current element and the next element should be compared i n each big permutation, n-1 times for each round. However, since each previous round has placed an element in the right position, there is no need to compare. If I have been cycled before, I elements should be placed at the end of the array correctly, so only n-1-i times are needed for each big permutation.
The code is as follows
Bubble sort:
#include <stdio.h> void bubblingSort(int arr[], int n) { int i, j, temp; // One element at a time to the end, n Elements, executing n second for (i = 0; i < n; ++i) { // The previous cycle has i When elements are sent to the end, they do not need to be compared again, so they are subtracted. In order to avoid overflow, they are subtracted by one for (j = 0; j < n - i - 1; ++j) { // If the current element is smaller than the latter, exchange if (arr[j] > arr[j + 1]) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } int main() { int i; int arr[10] = {5, 2, 3, 8, 1, 2, 6, 9, 3, 7}; bubblingSort(arr, 10); for (i = 0; i < 10; ++i) { printf("%d ", arr[i]); } return 0; }
As can be seen from the previous figure, the bubble sorting has been sorted in the next few rounds, but it is still in the cycle of verification. If no element is exchanged during each large arrangement, the array will be ordered and the loop can be terminated. Let's change the code and add a flag to determine the exchange of elements.
Bubble sorting after optimization:
#include <stdio.h> void bubblingSort(int arr[], int n) { int i, j, temp; int flag = 0; // flag Used to check whether there are moving elements in each cycle,0 For no move, 1 for move // One element at a time to the end, n Elements, executing n second for (i = 0; i < n; ++i) { flag = 0; // The previous cycle has i When elements are sent to the end, they do not need to be compared again, so they are subtracted. In order to avoid overflow, they are subtracted by one for (j = 0; j < n - i - 1; ++j) { // If the current element is smaller than the latter, exchange if (arr[j] > arr[j + 1]) { flag = 1; // With data exchange temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } // No data exchange, end ahead of time if (flag == 0) { break; } } } int main() { int i; int arr[10] = {5, 2, 3, 8, 1, 2, 6, 9, 3, 7}; bubblingSort(arr, 10); for (i = 0; i < 10; ++i) { printf("%d ", arr[i]); } return 0; }