一、二分查找和普通查找的优缺点
普通查找:原理简单,不需要数组有序;当元素个数很大时候,效率较低;
二分查找,需要数组有序排列,但是查找效率高;
二、二分查找实现
//查找指定元素在循序数组中的索引
function binary_search(arr,key){ var low=0, high=arr.length-1; while(low<=high){ //重新计算中间项索引位置 var mid=parseInt((high+low)/2); if(key==arr[mid]){ return mid; }else if(key>arr[mid]){ low=mid+1; }else if(key<arr[mid]){ high=mid-1; }else{ return -1; } } }; var arr=[1,2,3,4,5,6,7,8,9,10,11,12,15,29]; console.log(binary_search(arr,10));//9
三、快速排序
function quickSort(arr){ if(arr.length <= 1){ return arr; } var baseIndex = Math.floor(arr.length/2); var baseVal = arr.splice(baseIndex,1)[0];//基准元素 var left = []; var right = []; for(var i=0,len=arr.length; i<len; i++){ if(arr[i] <baseVal){ left.push(arr[i]); }else{ right.push(arr[i]); } } return quickSort(left).concat([baseVal],quickSort(right)); } var arr2 = [1,35,1,45,2,4,65,3,3,4,5,6,6,6]; console.log(quickSort(arr2));