Set found to false Set position to -1 Set index to 0 While index < number of elements and found is false If list[index]is equal to search value found = true position = index End If Add 1 to index End While Return position下面的函數 searchList 是一個 C++ 程式碼的範例,用於對一個整數陣列執行線性搜尋。陣列 list 最多具有 size 個元素,以下語句將搜尋它是否出現了儲存在 value 中的數位。如果找到該數位,則返回其陣列下標。否則,返回 -1,表示該值沒有出現在陣列中。
int searchList(const int list[], int size, int value) { int index = 0; //用作搜尋陣列的下標 int position = -1; //用於記錄搜尋值的位置 bool found = false; //指示值是否找到的標記 while (index < size && !found) { if (list [index] == value) // 如果找到該值 { found = true; // 設定標記 position = index; //記錄值的下標 } index++; //轉到下一個元素 } return position; // 返回該位置或-1 }注意,-1 被選作表示在陣列中找不到搜尋值的原因是:-1 不是有效的下標。其實,任何其他非有效的下標值也可以用來指示這一點。
// This program demonstrates the searchList function,which performs a linear search on an integer array. #include <iostream> using namespace std; // Function prototype int searchList(const int [], int, int); const int SIZE = 5; int main() { int tests[SIZE] = {87, 75, 98, 100, 82}; int results; // Holds the search results // Search the array for the value 100 results = searchList(tests, SIZE, 100); //If searchList returned -1, 100 was not found if (results == -1) cout << "You did not earn 100 points on any test.n"; else { // Otherwise results contains the subscript of the first 100 found in the array cout << "You earned 100 points on test "; cout << (results +1) << ".n"; } return 0; } int searchList(const int list[], int size, int value) { int index =0; // Used as a subscript to search array int position = -1; // Used to record position of search value bool found = false; // Flag to indicate if the value was found while (index < size && !found) { if (list[index] == value)// If the value is found { found = true; // Set the flag position = index; // Record the value's subscript } index++; // Go to the next element } return position; // Return the position, or -1 }程式輸出結果:
You earned 100 points on test 4.
N/2
次嘗試才能找到專案。如果一個陣列有 20 000 個元素,則線性搜尋平均需要對 10 000 個元素進行比較(N/2
是平均比較次數,最大比較次數總是 N)。當然,這是假定所搜尋的專案在陣列中必定存在的情況。