線性搜尋是一種透過順序檢查每個元素來尋找陣列中元素的簡單方法。
let data = [41, 23, 63, 42, 59]; const searchingElement = 59; let count = 0; for (let i = 0; i 0) { console.warn(`Element not found in current array!`); }
輸出: 在位置 5 找到元素
計算元素的出現次數:
let data = [41, 23, 63, 42, 59, 23]; let totalOccurrences = 0; const searchingElement = 63; for (const i in data) { if (data[i] === searchingElement) { totalOccurrences ; } } console.log(`Total occurrences of ${searchingElement} is ${totalOccurrences}`);
輸出: 63 的總出現次數為 1
線性搜尋很簡單,但對於大型資料集來說並不是最有效的。像二分搜尋這樣的高階演算法對於排序數組來說可以更有效。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3