每轮操作将该轮最大的数放入数组"末尾"
最差平均时间复杂度为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;
}
}
程序输出:
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