数据结构与算法分析(Java语言描述)(3)—— 冒泡排序

伪代码

do
  swapped = false
  for i = 1 to indexOfLastUnsortedElement-1
    if leftElement > rightElement
      swap(leftElement, rightElement)
      swapped = true
while swapped
    int n = arr.length;
    boolean swapped;
    do{
        swapped = false;
        for( int i = 1; i < n; i++){
            if ( arr[i-1].compaerTo(arr[i]) > 0){
                swap(arr, i, i-1);
                swapped = true;
            }
        }
        // 优化
        n--;
    }while(swapped);        

BubbleSort.java

package com.algorithm.sort;


public class BubbleSort {
    private BubbleSort() {

    }

    public static void sort(Integer[] arr) {
        int n = arr.length;
        boolean swapped;
        do {
            swapped = false;
            for (int i = 1; i < n; i++) {
                if (arr[i] < arr[i-1]) {
                    SortTestHelper.swap(arr, i-1, i);
                    swapped = true;
                }
            }

            // 优化, 每一趟Bubble Sort都将最大的元素放在了最后的位置
            // 所以下一次排序, 最后的元素可以不再考虑
            n--;
        }while(swapped);
    }

    // 单元测试
    public static void main(String[] args) {
        int N = 20000;
        Integer[] arr = SortTestHelper.generateRandomArray(N, 0, 100000);

        System.out.println("排序前的数组为:");
        SortTestHelper.printArray(arr);
        Long start = System.currentTimeMillis();
        BubbleSort.sort(arr);
        Long end = System.currentTimeMillis();
        System.out.println("-------------------------------------------");

        System.out.println("排序后的数组为:");
        SortTestHelper.printArray(arr);
        System.out.println("-------------------------------------------");

        System.out.println("排序后的数组是否有序:");
        if (SortTestHelper.isSorted(arr)){
            System.out.println("数组有序~");
        } else {
            System.out.println("数组无序!");
        }
        System.out.println("-------------------------------------------");

        System.out.println( "排序算法的运行时间为"+ " : " + (end-start) + "ms" );
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值