[JS common search algorithm]

1. Linear search

Linear search is the simplest search algorithm. Its basic idea is to traverse the data set to be searched from beginning to end to find the corresponding elements, and the time complexity is O(n).

Code:

function linearSearch(arr, target){
    
    
  for(let i = 0; i < arr.length; i++){
    
    
    if(arr[i] === target){
    
    
      return i;
    }
  }
  return -1;
}

2. Binary search

Binary search is also called binary search. Its basic idea is to sort the data set first, and then divide the data set into two parts from the middle. If the element to be searched is smaller than the middle value, continue to search in the left half, otherwise in the right half. Partially continue to search until the element is found or it is determined that the element does not exist, and the time complexity is O(logn).

Code:

function binarySearch(arr, target){
    
    
  let low = 0;
  let high = arr.length - 1;
  while(low <= high){
    
    
    let mid = Math.floor((low + high) / 2);
    if(target === arr[mid]){
    
    
      return mid;
    } else if(target < arr[mid]){
    
    
      high = mid - 1;
    } else {
    
    
      low = mid + 1;
    }
  }
  return -1;
}

3. Hash Lookup

Hash lookup is also called hash lookup. Its basic idea is to map the element to be looked up into a unique index value through a hash function, and then look up the element at the index position. If the element does not exist, return -1 . The time complexity of hash lookup is generally O(1), but it may degenerate to O(n) when dealing with hash collisions.

Code:

function hashSearch(arr, target){
    
    
  let hashTable = new Map();
  for(let i = 0; i < arr.length; i++){
    
    
    hashTable.set(arr[i], i);
  }
  if(hashTable.has(target)){
    
    
    return hashTable.get(target);
  } else {
    
    
    return -1;
  }
}

Guess you like

Origin blog.csdn.net/Ge_Daye/article/details/132237121