Bubble Sort
Topic description
Find and sort
Question: Enter any (user, grade) sequence, and you can get grades from high to low or from low to high. The same grades
are processed according to the rule of entering first and ranking first.
Example:
jack 70
peter 96
Tom 70
smith 67
High to Low Grade
peter 96
jack 70
Tom 70
smith 67
low to high
smith 67
jack 70
Tom 70
peter 96
Enter description:
Enter multiple lines, first enter the number of people to be sorted, then enter the sorting method 0 (descending order) or 1 (ascending order), then enter their names and grades respectively, separated by a space
Output description:
Output name and grade as specified, separated by a space
Example 1
enter
3 0 fang 90 the 50 and 70
output
fang 90 and 70 the 50
time complexity
If the initial state of the file is in positive order, the sorting can be completed in one scan. Minimum required number of keyword comparisons and number of record moves : , . Therefore, the best time complexity of bubble sort is .
If the original file is in reverse order, a pass sorting is required. Each time sorting needs to perform sub-key comparison (1≤i≤n-1), and each comparison must move the record three times to exchange the record position. In this case, both comparisons and moves are at their maximum:
The worst time complexity of bubble sort is . To sum up, so the total average time complexity of bubble sort is
Algorithm Stability
Bubble sort is to move small elements forward or large elements backward. The comparison is two adjacent elements. When the two elements are equal, the position of the element will not change, so the bubbling algorithm is a stable algorithm.