冒泡排序:
<script> var flag = false; var arr1 = [0,-90,89,36743,87,-89,9] for(var i=0;i<arr1.length-1;i++){ for(var j=0;j<arr1.length-1-i;j++){ if(arr1[j]>arr1[j+1]){ var temp = arr1[j]; arr1[j]=arr1[j+1] arr1[j+1]=temp; flag=true; } } if(flag){ flag=false; }else{ break; } } for(var i=0;i<arr1.length;i++){ document.write(arr1[i]+" ") } </script>
结果:
二分查找:
思路:找到数组中间的数(midVal),和你要查找的数(findVal)进行比较,如果midVal>findVal则说明findVal在数组的左边,就把给数组二分(就只在左边查找)
注意:前提条件:改数组必须是一个有序数组
// 非递归算法 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,23,44,86]; var result = binary_search(arr,10); alert(result); // 9 返回目标元素的索引值 // 递归算法 function binary_search(arr,low, high, key) { if (low > high){ return -1; } var mid = parseInt((high + low) / 2); if(arr[mid] == key){ return mid; }else if (arr[mid] > key){ high = mid - 1; return binary_search(arr, low, high, key); }else if (arr[mid] < key){ low = mid + 1; return binary_search(arr, low, high, key); } }; var arr = [1,2,3,4,5,6,7,8,9,10,11,23,44,86]; var result = binary_search(arr, 0, 13, 10); alert(result); // 9 返回目标元素的索引值
还可以这样写: var arr =[1,2,4,5,6,89]; function binarySearch(arr,findVal,leftIndex,rightIndex){ //防止无穷递归 if(leftIndex>rightIndex){ document.writeln("找不到"); return ; } //找到中间这个值 var midIndex = Math.floor((leftIndex+rightIndex)/2); //floor()是进行下舍入,即3.5就是3,ceil()为上舍入 console.log(midIndex) var midVal = arr[midIndex]; if(midVal>findVal){ //在左边找 binarySearch(arr,findVal,leftIndex,midIndex-1); }else if(midVal<findVal){ //再往右边找 binarySearch(arr,findVal,midIndex+1,rightIndex); }else{ document.writeln("找到下标为"+midIndex); return ; } } binarySearch(arr,2,0,arr.length-1);