Implementation of Bubble sorting and Bubble Sorting
1. Introduction to Bubble Sorting
Bubble sorting, repeated visits to the series to be sorted, compare two elements at a time, if their order is wrong, they will be exchanged. The work of visiting a sequence is repeated until there is no need for exchange, that is, the sequence has been sorted.
Ii. algorithm operations the Bubble Sorting Algorithm operates as follows: (from the back to the front)
- Compares adjacent elements. If the first is bigger than the second, exchange the two of them.
- Perform the same operation on each adjacent element, from the first to the last. At this point, the final element should be the largest number.
- Repeat the preceding steps for all elements except the last one.
- Continue to repeat the above steps for fewer and fewer elements until there is no need to compare them.
Iii. Time Complexity
If the initial state of the file is in positive order, a scan can complete the sorting. The number of keyword comparisons and record moves reach the minimum value: number of comparisons: n-1, and the number of moves is 0. Therefore, the best time complexity of Bubble Sorting is O (n ).
If the initial file is in reverse order, you need to sort the file in descending order of n-1. For each sort, we need to compare the n-I (1 ≤ I ≤ N-1) times of the keyword, and each comparison must move the record three times to reach the position of the exchange record. In this case, the number of comparisons and moves reaches the maximum value: the number of comparisons n * (n-1)/2, and the number of moves 3n * (n-1)/2.
The worst time complexity of Bubble Sorting is O (n * n ).
In summary, the average time complexity of Bubble Sorting is O (n * n ).
Iv. algorithm Stability
Bubble Sorting is to call a small element forward or a large element backward. The comparison is an adjacent comparison between two elements, and the Exchange also occurs between these two elements. Therefore, if the two elements are equal, there is no need to exchange them. If the two equal elements are not adjacent, they will not be exchanged even if they are adjacent through the two exchanges in the front, so the order of the same elements is not changed, so Bubble Sorting is a stable sorting algorithm.
V. Code Implementation
#include <stdio.h>#define SIZE 8 void bubble_sort(int a[], int n); void bubble_sort(int a[], int n){ int i, j, temp; for (j = 0; j < n - 1; j++) for (i = 0; i < n - 1 - j; i++) { if(a[i] > a[i + 1]) { temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; } }} int main(){ int number[SIZE] = {95, 45, 15, 78, 84, 51, 24, 12}; int i; bubble_sort(number, SIZE); for (i = 0; i < SIZE; i++) { printf("%d", number[i]); } printf("\n");}