疯狂java


您现在的位置: 疯狂软件 >> 新闻资讯 >> 正文

Java 冒泡算法和选择算法的比较


 

 
java 冒泡排序算法和选择排序算法的比较
冒泡排序算法:
for(int i = 0; i < numArray.length;i++;){
for(int j = i + 1; j < numArray.length; j++){
if(numArray[i] > numArray[j]){
int num = numArray[j];
numArray[j] = numArray[i];
numArray[i] = num;
}
}
}
选择排序算法:
int minIndex=0;
for(int i = 0; i < numArray.length - 1; i++){
minIndex = i;
for(int j = i + 1; j < numArray.length; j++){
if(numArray[i] > numArray[j]){
minIndex = j;
}
}
if(minIndex != i){
int num = numArray[minIndex];
numArray[minIndex] = numArray[i];
numArray[i] = num;
}
}
比较
情况一:
int[] numArray = new int[10000];
for(int n = 0; n < 10000; n++){
numArray[n] = (int) (Math.random()*1000 + 1);
}
结果 冒泡:234ms 选择109ms
情况二:
int[] numArray = new int[50000];
for(int n = 0; n < 50000; n++){
numArray[n] = (int) (Math.random()*1000 + 1);
}
结果 冒泡:2701ms 选择2995ms
情况三:
int[] numArray = new int[100000];
for(int n = 0; n < 100000; n++){
numArray[n] = (int) (Math.random()*1000 + 1);
}
结果 冒泡:10657ms 选择13071ms