1 冒泡排序简介
- 序列:{77,99,44,55,22,88,11,0,66,33}
- 一趟冒泡排序,会将一个最大的或最小的元素排到最右端,
- 于是多次进行冒泡排序后,序列右端将会变成有序的序列,
- 第一趟:77 44 55 22 88 11 0 66 33 [99]
- 第二趟:44 55 22 77 11 0 66 33 [88 99]
- 第三趟:44 22 55 11 0 66 33 [77 88 99]
- ...
- 最终趟:[0 11 22 33 44 55 66 77 88 99]
2 冒泡排序核心代码
/*
实际中,可能不需要全部趟数的排序,可以考虑设置一个flag变量,当某一趟排序完毕之后
flag:表示某一趟是否进行了冒泡交换swap(),
若这一趟没有进行冒泡交换swap(),即该序列已经整体有序了,
所以,可以提前结束 bubbleSort() 方法
*/
public void bubbleSort() { //冒泡排序代码
int out, in;
for (out = nElems - 1; out > 1; out--) {
//boolean flag = false; //每一趟排序,默认flag=false,即默认没有发生交换
for (in = 0; in < out; in++) {
if (a[in] > a[in + 1]) {
swap(in, in + 1);
//flag = true; //若发生了swap()交换,则flag=true
}
}
// if (flag==false){ //在一趟冒泡之后,检查flag,若==false,则这一趟没有发生交换
// break; //即列表序列已经整体有序,则退出for循环,提前结束冒泡排序
// }
}
}
3 具体实现
public class BubbleSortApp {
public static void main(String[] args) {
int maxSize = 11;
ArrayBub arr = new ArrayBub(maxSize);
int[] datas = {77, 99, 44, 55, 22, 88, 11, 0, 66, 33};
for (int data : datas) {
arr.insert(data);
}
System.out.println("这是未排序的数组:---------");
arr.display();
arr.bubbleSort();
System.out.println("这是已排序的数组:---------");
arr.display();
}
}
class ArrayBub {
private long[] a;
private int nElems; // 数组中数据的个数
//--------------------------------------------------------------------
public ArrayBub(int max) {
a = new long[max];
nElems = 0;
}
//--------------------------------------------------------------------
public void insert(long value) {
a[nElems] = value;
nElems++;
}
//--------------------------------------------------------------------
public void display() {
for (int j = 0; j < nElems; j++) {
System.out.printf("%d ", a[j]);
}
System.out.println();
}
//--------------------------------------------------------------------
public void bubbleSort() { //冒泡排序代码
int out, in;
for (out = nElems - 1; out > 1; out--) {
//boolean flag = false; //每一趟排序,默认flag=false,即默认没有发生交换
for (in = 0; in < out; in++) {
if (a[in] > a[in + 1]) {
swap(in, in + 1);
//flag = true; //若发生了swap()交换,则flag=true
}
}
// if (flag==false){ //在一趟冒泡之后,检查flag,若==false,则这一趟没有发生交换
// break; //即列表序列已经整体有序,则退出for循环,提前结束冒泡排序
// }
}
}
//--------------------------------------------------------------------
private void swap(int one, int two) { //注意这里是Java的对象引用
long temp = a[one]; //于是就直接通过temp进行了交换
a[one] = a[two];
a[two] = temp;
}
//--------------------------------------------------------------------
} // end class ArrayBub