Beispiele für gängige Suchalgorithmen in js

Hier sind einige Beispiele für gängige JavaScript-Suchalgorithmen:

1. Lineare Suche:

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

const arr = [4, 2, 6, 8, 1, 9];
console.log(linearSearch(arr, 6)); // 2
console.log(linearSearch(arr, 5)); // -1

2. Binäre Suche (vorausgesetzt, das Array ist sortiert):

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

const arr = [1, 2, 4, 6, 8, 9];
console.log(binarySearch(arr, 6)); // 3
console.log(binarySearch(arr, 5)); // -1

3. Hash-Suche (implementiert mithilfe einer Hash-Tabelle):

function hashSearch(arr, target) {
  const hashTable = {};
  const len = arr.length;
  for (let i = 0; i < len; i++) {
    hashTable[arr[i]] = i;
  }
  if (target in hashTable) {
    return hashTable[target];
  } else {
    return -1;
  }
}

const arr = [4, 2, 6, 8, 1, 9];
console.log(hashSearch(arr, 6)); // 2
console.log(hashSearch(arr, 5)); // -1

Dies sind Beispiele für einige gängige Suchalgorithmen. Abhängig von bestimmten Szenarien und Anforderungen kann die Auswahl eines geeigneten Suchalgorithmus die Sucheffizienz verbessern.

Ich hoffe, es hilft dir! Wenn Sie weitere Fragen haben, können Sie diese gerne stellen.
 

おすすめ

転載: blog.csdn.net/weixin_39273589/article/details/132538855