顺序搜索
function sequentialSearch(item, array) {
for(let i = 0; i < array.length;i++) {
if(item === array[i]) {
return i
}
}
return -1
}
console.log(sequentialSearch(2,[3,2,4,5,3]))
二分搜索
function binarySearch(item, array) {
let sortArray = quickSort(array)
let low = 0, hight = sortArray.lenght -1, mid, element
while(low < high) {
mid = Math.floor((low + high) /2)
element = sortArray[mid]
if(element < item) {
low = mid + 1
} else if(element > item) {
high = mid -1
} else {
return
}
}
}
binarySearch(13,[13,8,15,9,5,12,11])
内插搜索
function insertValueSearch(arr, left, right, findVal) {
if (left > right || findVal < arr[0]
|| findVal > arr[arr.length - 1]) {
return -1;
}
let mid = left + (right - left) * (findVal - arr[left]) / (arr[right] - arr[left]);
mid = Math.floor(mid);
let midVal = arr[mid];
if (findVal > midVal) {
return insertValueSearch(arr, mid + 1, right, findVal);
} else if (findVal < midVal) {
return insertValueSearch(arr, left, mid - 1, findVal);
} else {
return mid;
}
}
console.log(insertValueSearch([1,2,3,4,5,6,15], 0, 6,15))
|