package algorithm.sort;
/**
* 冒泡排序:重复地交换相邻的两个反序元素
* @author Administrator
*
*/
public class BubbleSort {
//对数组中指定位置的元素进行排序
public void bubbleSort(int[] a, int from, int end) {
for (int i = from; i<=end; i++) {
for (int j = end; j > i; j--) {
if (a[j-1] > a[j]) {
exchange(a, j-1, j);
}
}
}
}
//对整个数组排序
public void bubbleSort(int[] a) {
bubbleSort(a, 0, a.length-1);
}
//交换数组中的两个元素
public void exchange(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
//打印数组
public void printArr(String str, int[] a) {
System.out.print(str + "\t");
for(int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
System.out.println();
}
//测试数据
public static void main(String[] args) {
BubbleSort bs = new BubbleSort();
int[] a = {1,6,3,8,2,0};
bs.printArr("原始数组为:", a);
bs.bubbleSort(a);
bs.printArr("冒泡排序后:", a);
}
}