From 6f96bc08a61280b35fb865291bf5f6662d8ad9ea Mon Sep 17 00:00:00 2001 From: sourav singh <68277063+sourav9582@users.noreply.github.com> Date: Wed, 5 Oct 2022 14:03:31 +0530 Subject: [PATCH] Linear Search Algorithm Time complexity: O(N) Auxiliary Space: O(1) --- Linear Search Algorithm | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Linear Search Algorithm diff --git a/Linear Search Algorithm b/Linear Search Algorithm new file mode 100644 index 0000000..fff94b6 --- /dev/null +++ b/Linear Search Algorithm @@ -0,0 +1,27 @@ +//Linear Search is defined as a sequential search algorithm that starts at one +//end and goes through each element of a list until the desired element is found, +//otherwise the search continues till the end of the data set. +#include +using namespace std; + +int search(int arr[], int N, int x) +{ + int i; + for (i = 0; i < N; i++) + if (arr[i] == x) + return i; + return -1; +} + +int main(void) +{ + int arr[] = { 2, 3, 4, 10, 40 }; + int x = 10; + int N = sizeof(arr) / sizeof(arr[0]); + + int result = search(arr, N, x); + (result == -1) + ? cout << "Element is not present in array" + : cout << "Element is present at index " << result; + return 0; +}