您的位置:首页 > 编程语言 > Java开发

Program work 18. Bubble Sort in Java

2015-04-30 11:13 447 查看
每轮操作将该轮最大的数放入数组"末尾"

最差平均时间复杂度为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 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: