冒泡排序:
var arr=[5,0,-56,900,12,9000,-123,-1000];
var flag=false;
for(var i=0;i<arr.length-1;i++){
for(var j=0;j<arr.length-1-i;j++){
if(arr[j]>arr[j+1]){
var temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
flag=true;
}
}
if(flag){
flag=false;
}else{
break;
}
}
二分查找:
var arr=[1,2,3,4,5,6,7,8,9];
function binarySearch(arr,findVal,leftIndex,rightIndex){
if(leftIndex>=rightIndex){
alert("找不到");
return;
}
var midIndex=Math.floor((leftIndex+rightIndex)/2);
var midVal=arr[midIndex];
if(midVal>findVal){
binarySearch(arr,findVal,leftIndex,midIndex-1);
}else if(midVal<findVal){
binarySearch(arr,findVal,midIndex+1,rightIndex);
}else{
alert("找到了,下标为"+midIndex);
return;
}
}
binarySearch(arr,4,0,arr.length-1);