之前被某家公司面试问道:
问:知道冒泡排序吗?
答:知道啊。
问:写过吗?
答:写过啊。
问:那你知道冒泡排序优化吗?
答:知道一点……
哎……结果好像不满意……
今天我就来用Java写一下冒泡排序的一个优化方案,代码如下:
/**
* Created by Steven on 10/28/2014.
*/
public class BubbleSort {
public static void main(String[] args) {
int [] a={3,6,8,4,1,0,9,5,7,2};
for(int n: a){
System.out.print(n);
}
System.out.println();
sort(a);
for(int n: a){
System.out.print(n);
}
}
public static void sort(int [] a){
int len = a.length;
boolean flag = true;
while(flag){
flag = false;
for (int i=1;i<len;i++){
while(a[i-1] > a[i]){
int temp = a[i];
a[i] = a[i-1];
a[i-1] = temp;
flag = true;
}
}
len--;
}
}
}
其实从代码就能看到结果的差异了,用标志位flag 来判断 由于数值大小 两值有没有进行交换,没有的话直接逃出,跳到下一次循环。
这样就省去每一个数值进行比较的次数,显然可以达到优化了。
此算法是最简单的设计了,有什么更好的设计,望各位看官提出来进行交流……