Implementation of bubble sorting algorithm in Java

Bubble sort:

That is, two adjacent elements are compared one by one according to the index. If it is greater than / less than (depending on whether ascending or descending order is required), it will be replaced. Otherwise, no change will be made. In this round, n-1 times are compared, and N is equal to the number of elements; n-2,n-3 ... Until the last round, I compared it once, so  The number of comparisons decreases: from n-1 to 1, the total number of comparisons is: 1 + 2 + 3 +... + (n-1), which is calculated by the equal difference formula: (1 + n-1) / 2 * (n-1) = = > n / 2 * (n-1) = > (n ^ 2-N) * 0.5. The large o represents the time complexity of the algorithm: O (n ^ 2), ignoring the coefficient 0.5 and the constant - n.

Algorithmic thought

It repeatedly visits the sequence to be sorted, compares two elements at a time, and exchanges them if they are in the wrong order. The work of visiting the sequence is repeated until there is no need to exchange, that is, the sequence has been sorted.

The name of this algorithm comes from the fact that the smaller elements will slowly "float" to the top of the sequence through exchange.

The code is as follows:

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>