思想
- 前后相邻两数组进行比较
- 前一相比后一项大或小
- 交换数组
- 每一次都能找出一个最大值或最小值
- 在剩余的数组中继续循环查找
5 | 3 | 8 | 7 | 1 |
---|
3 | 5 | 7 | 1 | 8 |
3 | 5 | 1 | 7 | 8 |
3 | 1 | 5 | 7 | 8 |
1 | 3 | 5 | 7 | 8 |
实现
public class Bubble {
public static void sort(int[] a) {
int N = a.length;
for (int i = 0; i < N - 1; i++) {
for (int j = 0; j < N - 1 - i; j++) {
if (less(a[j + 1], a[j])) {
exch(a, j + 1, j);
}
}
}
}
public static boolean less(Comparable v, Comparable w) {
return v.compareTo(w) < 0;
}
public static void exch(int[] a, int i, int j) {
Comparable t = a[i];
a[i] = a[j];
a[j] = (int) t;
}
private static void show(int[] a) {
for (int value : a) {
System.out.println(value);
}
}
public static boolean isSorted(int[] a) {
for (int i = 1; i < a.length; i++) {
if (less(a[i], a[i - 1])) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int[] a = init.random(1000);
Stopwatch time = new Stopwatch();
sort(a);
double timer = time.elapsedTime();
if (isSorted(a)) {
show(a);
System.out.println("time: " + timer);
}
else {
System.out.println("false");
}
}
}