Bubble sort idea (small to large):
Compares adjacent two elements, exchanging their positions if the first element is larger than the second element. First, starting with the first element, the first element is compared to the second element, and if the first element is larger than the second element, the position is swapped; next, the second, third element, the big one, and so on, until the last two. At the end of the first comparison, the largest element is placed in the last position. Next, proceed to the second order, from the first element to the penultimate element (because the last one is already the largest), perform the above steps. Proceed in turn.
The optimal worst-case average time complexity at this point is O (n^2).
Optimization: Adds a flag bit, when swapping elements is true, no interchange is false, sort ends.
At this time, the optimal time complexity of the optimization algorithm is O (n), the worst and the average is O (n^2).
The bubble sort and its optimization (Java implementation) for getting started with sorting algorithms