首页 / 算法 / 算法 - 冒泡排序(Java)
算法 - 冒泡排序(Java)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了算法 - 冒泡排序(Java),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2026字,纯文字阅读大概需要3分钟。
内容图文
分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.net
package chimomo.learning.java.algorithm.sort;
/**
* @author Chimomo
*
* <p>
* Bubble sort is a kind of simple sort algorithm in computer science. It
* repeatedly visit the sequence to be sorted, compare two elements each time,
* swap them if their order is wrong, until no elements need to be swapped. The
* bigger element will rise to top by swapping like bubble, so it names.
* </p>
*
* The bubble sort algorithm designed as following:
* <li>
* 1. Compare the two adjacent elements as a pair, from the first pair to last
* pair, swap the two if the first one is bigger than the second one. Then, the
* last element must be the biggest, remove the biggest one from unordered
* region.
* </li>
* <li>
* 2. Repeat step1 on the elements in the unordered region until no element pair
* need to be compared.
* </li>
*
* The time complexity of bubble sort is O(n^2).
*
* <p>
* Stability: Bubble sort is swapping bigger element backward. Comparing is
* comparing the adjacent two elements, swapping is also in the adjacent two
* elements. So, if the two adjacent elements equal, you will not swap them. And
* if the two equal elements are not adjacent, even though they are adjacent by
* swapping the front other elements, you still will not swap them. The equal
* elements order are not changed in sorting, so bubble sort is stable.
* </p>
*/
public class BubbleSort {
/**
* The bubble sort.
* @param a The array to be sorted
*/
public static void sort(int[] a) {
System.out.println("In Bubble Sort:");
// The outer loop: Limit the count of elements in each bubble sort comparison.
for (int i = a.length - 1; i >= 1; i--) {
// The inner loop: Comparing the elements whose subscript from 0 to i-1.
for (int j = 0; j <= i - 1; j++) {
// The sorting process.
if (a[j] > a[j + 1]) {
int t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
System.out.println(String.format("Round {0}: ", a.length - i));
for (int e : a) {
System.out.print(e + " ");
}
System.out.println();
}
}
}
内容总结
以上是互联网集市为您收集整理的算法 - 冒泡排序(Java)全部内容,希望文章能够帮你解决算法 - 冒泡排序(Java)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。