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;
        }
    
    }
  • 相关阅读:
    perl教程
    信号量(semaphore)——POSIX信号量和System V信号量
    (C#习题) 杂题1
    (C#) 操作XML之遍历
    (C# 基础) Solution and Project
    (C#)枚举 Enumerations
    (WPF) 窗口间传参数
    (C#) 操作XML之查找
    (C#习题) 字符串
    (C#) VS类视图和对象浏览器图标
  • 原文地址:https://www.cnblogs.com/yeahwell/p/5609470.html
Copyright © 2011-2022 走看看