Algorithms_in_C++ 1.0.0
Set of algorithms implemented in C++.
linear_search.cpp File Reference

Linear search algorithm More...

#include <iostream>
Include dependency graph for linear_search.cpp:

Functions

int LinearSearch (int *array, int size, int key)
 
int main ()
 

Detailed Description

Function Documentation

◆ LinearSearch()

int LinearSearch ( int *  array,
int  size,
int  key 
)

Algorithm implementation

Parameters
[in]arrayarray to search in
[in]sizelength of array
[in]keykey value to search for
Returns
index where the key-value occurs in the array
-1 if key-value not found
16 {
17 for (int i = 0; i < size; ++i) {
18 if (array[i] == key) {
19 return i;
20 }
21 }
22
23 return -1;
24}

◆ main()

int main ( void  )

main function

27 {
28 int size;
29 std::cout << "\nEnter the size of the Array : ";
30 std::cin >> size;
31
32 int *array = new int[size];
33 int key;
34
35 // Input array
36 std::cout << "\nEnter the Array of " << size << " numbers : ";
37 for (int i = 0; i < size; i++) {
38 std::cin >> array[i];
39 }
40
41 std::cout << "\nEnter the number to be searched : ";
42 std::cin >> key;
43
44 int index = LinearSearch(array, size, key);
45 if (index != -1) {
46 std::cout << "\nNumber found at index : " << index;
47 } else {
48 std::cout << "\nNot found";
49 }
50
51 delete[] array;
52 return 0;
53}
int LinearSearch(int *array, int size, int key)
Definition: linear_search.cpp:16