Home > Backend Development > C++ > body text

C/C++ program for linear search?

王林
Release: 2023-09-05 17:05:06
forward
858 people have browsed it

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.
Copy after login

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;
}
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template