参考资料:https://www.geeksforgeeks.org/bubble-sort/
Arrays.sort()原理: https://www.cnblogs.com/baichunyu/p/11935995.html
百度百科: https://baike.baidu.com/item/%E5%86%92%E6%B3%A1%E6%8E%92%E5%BA%8F/4602306?fr=aladdin

算法原理

  1. 比较相邻的元素。如果第一个比第二个大,就交换他们两个。
  2. 对每一对相邻元素做同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。
  3. 针对所有的元素重复以上的步骤,除了最后一个。
  4. 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。

    时间复杂度

    若文件的初始状态是正序的,一趟扫描即可完成排序。所以,冒泡排序最好的时间复杂度O(n)
    若初始文件是反序的,需要进行_n-1_次排序,每次排序要进行_n-i_次元素比较。所以,冒泡排序最坏时间复杂度为O(n2)。
    综上,冒泡排序平均时间复杂度为O(n2)。

算法稳定性

冒泡排序就是把小的元素往前调或者把大的元素往后调。比较是相邻的两个元素比较,交换也发生在这两个元素之间。所以,如果两个元素相等,是不会再交换的;如果两个相等的元素没有相邻,那么即使通过前面的两两交换把两个相邻起来,这时候也不会交换,所以相同元素的前后顺序并没有改变,所以冒泡排序是一种稳定排序算法。

普通写法1

  1. /**
  2. * 冒泡排序练习
  3. */
  4. public class MyBubbleSort {
  5. public static void main(String[] args) {
  6. int[] ns = {66, 28, 23, 73, 28, 41, 14, 25, 28, 72, 80};
  7. // 排序前:
  8. System.out.println(Arrays.toString(ns));
  9. // 冒泡排序
  10. // 外层循环到数组倒数第二个数(包含),最后一个数不用再比较(因为前面已经比较过了)
  11. for (int i = 0; i < ns.length - 1; i++) {
  12. // 内层循环到数组倒数第二个数(包含),最后一个数的比较在if作用
  13. for (int j = 0; j < ns.length - i - 1; j++) {
  14. // 当j=ns.length-2的时候,j+1=ns.length-1,也就是比较了最后一个数
  15. if (ns[j] > ns[j + 1]) {
  16. // 借助第三个临时变量,互换两数
  17. int temp = ns[j];
  18. ns[j] = ns[j + 1];
  19. ns[j + 1] = temp;
  20. }
  21. }
  22. }
  23. // 排序后
  24. System.out.println(Arrays.toString(ns));
  25. }
  26. }

普通写法2

  1. /**
  2. * 冒泡排序练习2
  3. */
  4. public class MyBubbleSort2 {
  5. public static void main(String[] args) {
  6. int[] ns = {66, 28, 23, 73, 28, 41, 14, 25, 28, 72, 80};
  7. // 排序前:
  8. System.out.println(Arrays.toString(ns));
  9. // 冒泡排序
  10. // 外层循环到数组倒数第二个数(包含),最后一个数不用再比较(因为前面已经比较过了)
  11. for (int i = 0; i < ns.length - 1; i++) {
  12. // 内层循环,让j从i的后面那个数开始比较
  13. for (int j = i+1; j < ns.length; j++) {
  14. if (ns[i] > ns[j]) {
  15. // 借助第三个临时变量,互换两数
  16. int temp = ns[j];
  17. ns[j] = ns[i];
  18. ns[i] = temp;
  19. }
  20. }
  21. }
  22. // 排序后
  23. System.out.println(Arrays.toString(ns));
  24. }
  25. }

优化写法

  1. public class MyBubbleSort3 {
  2. public static void main(String[] args) {
  3. int[] ns = {66, 28, 23, 73, 28, 41, 14, 25, 28, 72, 80};
  4. int i, j, temp;
  5. boolean swapped;
  6. // 排序前:
  7. System.out.println(Arrays.toString(ns));
  8. for (i = 0; i < ns.length - 1; i++) {
  9. swapped = false;
  10. for (j = 0; j < ns.length - i - 1; j++) {
  11. if (ns[j] > ns[j + 1]) {
  12. // 交换ns[j]和ns[j+1]
  13. temp = ns[j];
  14. ns[j] = ns[j + 1];
  15. ns[j + 1] = temp;
  16. swapped = true;
  17. }
  18. }
  19. // 如果,结对比较没有发生交换动作,说明这一轮的都是顺序对的,没有必要再进行下一轮比较了,直接跳出循环
  20. if (swapped == false) break;
  21. }
  22. // 排序后
  23. System.out.println(Arrays.toString(ns));
  24. }
  25. }