1.
1 var arr = prompt("请输入一个数组(以“,”隔开):").split(",").map(function(data){ 2 return +data;}).sort(compare); 3 console.log("输入的数组,排序后是:"+arr); 4 5 var key=parseInt(prompt("请输入一个要查找的数字:")); 6 console.log("要查找的数字是:"+key); 7 8 var low=0,high=arr.length-1,mid; 9 10 arr.map(function(data){ 11 if(data==key){ 12 console.log("您要查找的数字排在第 "+fun(arr,key,low,high)+" 位"); 13 } 14 }) 15 16 function compare(value1,value2){ 17 if(value1<value2){ 18 return -1; 19 }else if(value1>value2){ 20 return 1; 21 }else{ 22 return 0; 23 } 24 } 25 26 function fun(arr,key,low,high){ 27 mid=Math.floor((low+high)/2); 28 if(arr[mid]==key){ 29 return mid; 30 }else if(arr[mid]<key){ 31 low=mid+1; 32 return fun(arr,key,low,high); 33 }else{ 34 high=mid-1; 35 return fun(arr,key,low,high); 36 } 37 }
时间: 2024-11-13 12:36:51