current position:Home>JavaScript implements search algorithm, sequential search and binary search

JavaScript implements search algorithm, sequential search and binary search

2022-04-29 04:26:51@huihui_ new

Sequential search
Search from front to back in order
Time complexity :O(N)

Array.prototype.sequentialSearch = function(item){
    
	for(let i = 0; i<this.length;i++) {
    
		if(this[i] === item) {
    
			return i
		}
	}
	return -1
}

const res = [1, 2, 3, 4, 5].sequentialSearch(3);

Two point search
Start with the middle element of the array , If the intermediate element is exactly the target value , Then the search ends .
If the target value is greater than or less than the intermediate element , Search in the half array greater than or less than the intermediate element .
Time complexity :O(logN)

Array.prototype.binarySearch = function (item) {
    
  // this.sort()
  let low = 0;
  let height = this.length - 1;
  while (low <= height) {
    
    const mid = Math.floor((low + high) / 2);
    const element = this[mid];
    if (element < item) {
    
      low = mid + 1;
    } else if (element > item) {
    
      high = mid - 1;
    } else {
    
      return mid;
    }
  }
  return -1;
};
const res = [1, 2, 3, 4, 5].binarySearch;

copyright notice
author[@huihui_ new],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/117/202204270551339773.html

Random recommended