首先来看一段普通的冒泡排序程序。这个程序算法上可以实现排序,但是算法比较复杂。例如如果初始数列已经有序,那么执行这个程序依然做n*n次比较。
public class BubbleSort {
private Number source[];
public BubbleSort(Number source[]) {
this.source = source;
}
/**
* arithmetic
*
* @return
*/
public Number[] doSort() {
int length = source.length;
for (int i = length-1; i >1; i--) {
for (int j = 0; j
if (source[j].doubleValue() > source[j + 1].doubleValue()) {
Number tmp = source[j];
source[j] = source[j + 1];
source[j + 1] = tmp;
}
}
return source;
}
/**
* Display the result
*
* @param source
*/
public static void display(Number[] source) {
for (int i = 0; i < source.length; i++)
System.out.println("source[" + i + "] = " + source[i]);
}
public static void main(String[] args) {
Number[] source = { new Integer(3), new Double(6.56), new Float(10.19),
new Long(11), new Integer("12"), new Double(12.999999999) };
System.out.println("Before sorting:::");
BubbleSort.display(source);
BubbleSort bubble = new BubbleSort(source);
System.out.println("After sorting:::");
source = bubble.doSort();
BubbleSort.display(source);
}
}
如何完善解决这个问题呢?其实很简单只需设置交换标志即可,初始值是false,在一次遍历中如果有数据交换,则置为true,如果没有交换,则直接退出。doSort()方法改写如下:
public Number[] doSort() {
int length = source.length;
for (int i = length-1; i >1; i--) {
boolean exchange=false;
for (int j = 0; j
if (source[j].doubleValue() > source[j + 1].doubleValue()) {
Number tmp = source[j];
source[j] = source[j + 1];
source[j + 1] = tmp;
exchange=true;
}
if(!exchange)
return source;
}
return source;
}
如果有什么说的不当的地方或者还有更加完善的改进方法,欢迎大家指出。嘿嘿