線性查詢的 C/C++ 程式?


線上性查詢演算法中,我們將目標元素與陣列的每個元素進行比較。如果找到該元素,則顯示其位置。

線性查詢的最壞時間複雜度為 O(n)。

Input: arr[] = { 12, 35, 69, 74, 165, 54}
Sea=165
Output: 165 is present at location 5.

說明

線性查詢(搜尋演算法)用於查詢給定數字是否出現在陣列中,如果存在,則查詢它在陣列中的位置。它也被稱為順序查詢。這個過程進行起來非常簡單:在找到目標元素或列表結束之前,我們持續將每個元素與目標元素進行比較。

示例

#include <iostream>
using namespace std;
int main() {
   int sea, c, n=6;
   int arr[] = { 12, 35, 69, 74, 165, 54};
   sea=165;
   for (c = 0; c < n; c++) {
      if (arr[c] == sea) {
         printf("%d is present at location %d.\n", search, c+1);
         break;
      }
   }
   if (c == n)
      printf("%d isn't present in the array.\n", search);
   return 0;
}

更新於:2019 年 8 月 20 日

超過 9K 瀏覽

激發你的 職業生涯

完成課程以取得認證

開始學習
廣告
© . All rights reserved.