package hello;
import java.util.Random;
/**
*冒泡排序 时间级别:O(N*N)【注】效率低,排序速度慢
*/
class BubbleSort {
long[] a;
int nElems;
// constructor
public BubbleSort(int max) {
a = new long[max];
nElems = 0;
}
// put element into array
public void insert(long value) {
a[nElems] = value;
nElems++;
}
// displays array contents
public void display() {
for (int i = 0; i < nElems; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
/**
* 思路: 将最小的数据项放在数组的最开始(数组下标为0),并将最大数据项放在
* 数组的最后(数组下标为nElems-1).外层for循环的计数器out从数组的
* 最后开始,即out等于nElems-1,每经过一次循环out-1.下标大于out的
* 数据项都已经是排好序的了.变量out在每完成一次内部循环(计数器为in)后 就左移一位,因此算法就不在处理那些已经排好序的数据.
* 内层for循环计数器in从数组的最开始算起,即in=0,每完成一次内部循环体加1,
* 当它等于out时结束一次循环.在内层for循环体中,数组下标为in和in+1的两个数据项
* 进行比较,如果下标为in的数据项大于下标为in+1的数据项,则交换两个数据项.
*/
public void bubbleSort() {
int out, in;
for (out = nElems - 1; out > 1; out--) {
// outer loop(backward)
for (in = 0; in < out; in++) {
// inner loop(forward)
if (a[in] > a[in + 1]) {// out of order?
swap(in, in + 1);// swap them
}
}
}
}
void swap(int one, int two) {
long temp = a[one];
a[one] = a[two];
a[two] = temp;
}
}
/*
*
* 测试
*/
public class BubbleSortApp {
public static void main(String[] args) {
int maxSize = 100;
BubbleSort arr = new BubbleSort(maxSize);
Random r = new Random();
// insert 10 items
for (int i = 0; i < 10; i++) {
arr.insert(r.nextInt(100));
}
arr.display();
arr.bubbleSort();
arr.display();
}
}