Program work 18. Bubble Sort in Java

每轮操作将该轮最大的数放入数组"末尾"


最差平均时间复杂度为O(n*n)

最好时间复杂度为O(n), 需要加标记, 且数组已排好序的情况下


Pseudocode:

bubblesort (A : list[0..n-1]) {
    var i, j;
    for i from 0 to n-2 {
        for j from 0 to n-2-i { 
            if (A[j] > A[j+1])
                swap(A[j], A[j+1])
        }
    }
}

Java:

package ncku.cdc.sorting;

import java.util.Random;

public class BubbleSort {
private int[] sequence;
  
  public BubbleSort(int size, int range) {
    sequence = new int[size];
    Random rand = new Random();
    for (int i = 0; i < size; i++) {
      sequence[i] = rand.nextInt(range);
    }
  }
  
  public static void main(String[] args) {
    int size = Integer.valueOf(args[0]);
    int range = Integer.valueOf(args[1]);
    BubbleSort bubble = new BubbleSort(size, range);

    System.out.println("before bubbleSort:");
    SortingTools.validation(bubble.getSequence(), 0);

    bubble.bubbleSort(bubble.getSequence());
    
    System.out.println("after bubbleSort:");
    SortingTools.validation(bubble.getSequence(), 0);
  }
  
  public void bubbleSort(int[] arr) {
    int len = arr.length;
    for (int i = 0; i < len - 1; i++) {
      for (int j = 1; j <= len - i - 1; j++) {
        if (arr[j - 1] > arr[j]) { swap(arr, j - 1, j); }
      }
    }
  }

  private void swap(int[] arr, int i, int j) {
    int t = arr[i];
    arr[i] = arr[j];
    arr[j] = t;
  }
  
  public int[] getSequence() {
    return sequence;
  }
}


程序输入: 35 200. 表示生成长度为35, 数字范围为[0, 200)的数组

程序输出:

before bubbleSort:
32 62 38 19 89 86 162 135 85 125 167 103 122 163 25 133 40 149 41 122 53 189 14 45 198 17 111 81 112 86 77 115 5 182 190 
after bubbleSort:
5 14 17 19 25 32 38 40 41 45 53 62 77 81 85 86 86 89 103 111 112 115 122 122 125 133 135 149 162 163 167 182 189 190 198 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值