冒泡排序(BubbleSort)的基本概念是:
依次比较相邻的两个数,将小数放在前面,大数放在后面。
即在第一趟:
首先比较第1个和第2个数,将小数放前,大数放后。
然后比较第2个数和第3个数,将小数放前,大数放后,如此继续,直至比较最后两个数,将小数放前,大数放后。
至此第一趟结束,将最大的数放到了最后。
在第二趟:
仍从第一对数开始比较(因为可能由于第2个数和第3个数的交换,使得第1个数不再小于第2个数),
将小数放前,大数放后,一直比较到倒数第二个数(倒数第一的位置上已经是最大的),第二趟结束,
在倒数第二的位置上得到一个新的最大数(其实在整个数列中是第二大的数)。
如此下去,重复以上过程,直至最终完成排序。
public class BubbleSort {
public final static void swap(int a[],int i,int j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public final static void bubbleSort(int a[],int low,int high){
for(int i = high; --i > low;){
System.out.println("------------------------");
System.out.println("i = " + i);
for(int j = low; ++j <= i; ){
if(a[j]<a[j-1]){
swap(a,j,j-1);
}
}
System.out.println(Arrays.toString(a));
}
}
public final static void bubbleSort(int a[]){
bubbleSort(a,0,a.length);
}
public static void main(String[] args) {
int a[] = new int[]{5,4,3,2,1};
bubbleSort(a);
}
}
运行结果是:
------------------------
i = 4
[4, 3, 2, 1, 5]
------------------------
i = 3
[3, 2, 1, 4, 5]
------------------------
i = 2
[2, 1, 3, 4, 5]
------------------------
i = 1
[1, 2, 3, 4, 5]
优化处理,冒泡是最基本的排序,优化点可以判断序列是否有序,有序则结束
public class BubbleSort {
public final static void swap(int a[], int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public final static void bubbleSort(int a[], int low, int high) {
for (int i = high; --i > low;) {
boolean sorted = true;
for (int j = low; ++j <= i;) {
if (a[j] < a[j - 1]) {
swap(a, j, j - 1);
sorted = false;
}
}
if (sorted)
break;
}
}
public final static void bubbleSort(int a[]) {
bubbleSort(a, 0, a.length);
}
public static void main(String[] args) {
int a[] = new int[] { 1, 2, 3, 5, 4 };
bubbleSort(a);
}
}