Home  >  Article  >  Backend Development  >  C/C++ program for linear search?

C/C++ program for linear search?

王林
王林forward
2023-09-05 17:05:06784browse

C/C++ program for linear search?

In linear search algorithm, we compare the target element with each element of the array. If the element is found, its position is displayed.

The worst-case time complexity of linear search is O(n).

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

Description

Linear search (search algorithm) to find whether a given number exists in an array and if so where does it appear. It is also called sequential search. It's simple and works like this: we keep comparing each element with the element we are searching for until it is found or the list ends.

Example

#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&#39;t present in the array.\n", search);
   return 0;
}

The above is the detailed content of C/C++ program for linear search?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete