zoukankan      html  css  js  c++  java
  • 《OD学算法》排序之冒泡排序

    冒泡排序

    一语中的:丢一把沙子,轻的物体往上浮。

    基本思想:通过无序区中相邻记录关键字间的比较和位置的交换,使关键字最小的记录如气泡一般逐渐往上“漂浮”直至“水面”。 

    代码示例:

    import java.util.Arrays;
    
    public class BubbleSort {
    
        public int[] bubbleSort(int[] array) {
            int length = array.length;
            boolean swapped = true;
            int compareCount = 0;
            do {
                swapped = false;
                for (int i = 0; i < length - 1; i++) {
                    System.out.println("compare(" + array[i] + "," + array[i + 1] + ")");
                    if (array[i] > array[i + 1]) {
                        int temp = array[i];
                        array[i] = array[i + 1];
                        array[i + 1] = temp;
                        swapped = true;
                    }
                    compareCount++;
                    System.out.println("第" + i + "趟 array=" + Arrays.toString(array));
                }
            } while (swapped);
            System.out.println("冒泡排序比较次数=" + compareCount);
            return array;
        }
        
        public int[] bubbleSort2(int[] array) {
            int length = array.length;
            int compareCount = 0;
            for(int j = 0; j < length - 1; j++){
                for(int i = 0; i < length - j - 1; i++){
                    System.out.println("compare(" + array[i] + "," + array[i + 1] + ")");
                    if(array[i] > array[i + 1]){
                        int temp = array[i];
                        array[i] = array[i + 1];
                        array[i + 1] = temp;
                    }
                    compareCount++;
                }
                System.out.println("第" + j + "趟 array=" + Arrays.toString(array));
            }
            System.out.println("冒泡排序比较次数=" + compareCount);
            return array;
        }
    
    }
  • 相关阅读:
    javascript DOM事件总结
    MySQL索引优化实例说明
    CSV导出大量数据
    最详细的PHP flush()与ob
    XSS攻击(跨站攻击)
    MySQL视图
    MySQL索引
    待整理
    Height、clientHeight、scrollHeight、offsetHeight 、scrollTop、offsetTop
    Cookie和Session的区别
  • 原文地址:https://www.cnblogs.com/yeahwell/p/5609470.html
Copyright © 2011-2022 走看看