C/C++ Program for Linear Search?

CC++Server Side ProgrammingProgramming

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

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

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

Explanation

linear search (Searching algorithm) which is used to find whether a given number is present in an array and if it is present then at what location it occurs. It is also known as sequential search. It is straightforward and works as follows: We keep on comparing each element with the element to search 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't present in the array.\n", search);
   return 0;
}
raja
Published on 20-Aug-2019 09:00:05
Advertisements