Java冒泡排序代码整理:
package boke.sort;
/**
* 冒泡排序
*
* @since jdk1.5及其以上
* @author 毛正吉
* @version 1.0
* @date 2010.05.24
*
*/
public class BubbleSort {
/**
* @param args
*/
public static void main(String[] args) {
int maxSize = 100;
BubbleSort bs = new BubbleSort(maxSize);
bs.insert(77);
bs.insert(66);
bs.insert(22);
bs.insert(99);
bs.insert(85);
bs.insert(37);
bs.insert(75);
bs.insert(64);
bs.insert(15);
bs.insert(35);
bs.output(); // 原始输出
bs.bubbleSort(); // 排序
bs.output(); // 排序输出
}
private long[] a; // 整型数据容器
private int nElems; // 元素个数
/**
* 构造方法
*
* @param maxSize
*/
public BubbleSort(int maxSize) {
a = new long[maxSize];
nElems = 0;
}
/**
* 容器放入数据
*
* @param value
*/
public void insert(long value) {
a[nElems++] = value;
}
/**
* 输出容器数据
*/
public void output() {
for (int j = 0; j < nElems; j++) {
System.out.print(a[j] + " ");
}
System.out.println("");
}
/**
* 冒泡排序
*/
public void bubbleSort() {
int out, in;
for (out = nElems - 1; out > 1; out--) {
for (in = 0; in < out; in++) {
if (a[in] > a[in + 1]) {
swap(in, in + 1);
}
}
}
}
/**
* 交换
*
* @param in
* @param i
*/
private void swap(int one, int two) {
long temp = a[one];
a[one] = a[two];
a[two] = temp;
}
}