public class test {
public static void bubbleSort(int[] A) {
int n = A.length;
int last = n - 1;
for (int i = 0; i < n; i++) {System.out.println(i);
int k = 0;
for (int j = 0; j < last; j++) {
if (A[j + 1] < A[j]) {
int temp = A[j];
A[j] = A[j + 1];
A[j + 1] = temp;
k = j;
}
}
if(k == 0) break;
last = k;
}
}
public static void bidirectionalBubbleSort(int[] A) {
int n = A.length;
int first = 0;
int last = n - 1;
for (int i = 0; i < n; i++) {
int k = 0;
for (int j = first; j < last; j++) {
if (A[j + 1] < A[j]) {
int temp = A[j];
A[j] = A[j + 1];
A[j + 1] = temp;
k = j;
}
}
last = k;
for(int m = last; m > first; m--){
if(A[m] < A[m-1]){
int temp = A[m];
A[m] = A[m-1];
A[m-1] = temp;
k = m;
}
}
first = k;
if(first >= last) break;
}
}
public static void main(String[] args) {
int[] Test = new int[] { 7, 4, 6, 8, 5, 3, 9, 0, 2, 1 };
bubbleSort(Test);
// bidirectionalBubbleSort(Test);
for (int i = 0; i < Test.length; i++) {
System.out.printf("%d\t", Test[i]);
}
}
}
用last标记最后一次调整的位置
双向冒泡排序
在原基础上 从头至尾调整完后 再从尾至头调整一遍
同时再用一个first标记最后一次调整