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;
        }
    
    }
  • 相关阅读:
    ios 学习小笔记
    object c 2.0 @property属性
    uiPickerView 滚动盘
    ios 文件操作
    ios多窗体项目
    Linux命令
    Mina的使用
    设计模式学习总结访问者模式(Visitor Method)
    socket, nio socket 及nio socket框架MINA总结
    UML类图与类的关系详解UML一波流系列(转转)
  • 原文地址:https://www.cnblogs.com/yeahwell/p/5609470.html
Copyright © 2011-2022 走看看