TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
linear_search.cpp
Go to the documentation of this file.
1
10#include <cassert>
11#include <iostream>
12
21int LinearSearch(int *array, int size, int key) {
22 for (int i = 0; i < size; ++i) {
23 if (array[i] == key) {
24 return i;
25 }
26 }
27
28 /* We reach here only in case element is not present in array, return an
29 * invalid entry in that case*/
30 return -1;
31}
32
37static void tests() {
38 int size = 4;
39 int *array = new int[size];
40 for (int i = 0; i < size; i++) {
41 array[i] = i;
42 }
43
44 assert(LinearSearch(array, size, 0) == 0);
45 assert(LinearSearch(array, size, 1) == 1);
46 assert(LinearSearch(array, size, 2) == 2);
47
48 size = 6;
49 for (int i = 0; i < size; i++) {
50 array[i] = i;
51 }
52
53 assert(LinearSearch(array, size, 3) == 3);
54 assert(LinearSearch(array, size, 1) == 1);
55 assert(LinearSearch(array, size, 5) == 5);
56
57 std::cout << "All tests have successfully passed!\n";
58 delete[] array; // free memory up
59}
60
65int main() {
66 int mode = 0;
67
68 std::cout << "Choose mode\n";
69 std::cout << "Self-test mode (1), interactive mode (2): ";
70
71 std::cin >> mode;
72
73 if (mode == 2) {
74 int size = 0;
75 std::cout << "\nEnter the size of the array [in range 1-30 ]: ";
76 std::cin >> size;
77
78 while (size <= 0 || size > 30) {
79 std::cout << "Size can only be 1-30. Please choose another value: ";
80 std::cin >> size;
81 }
82
83 int *array = new int[size];
84 int key = 0;
85
86 // Input for the array elements
87 std::cout << "Enter the array of " << size << " numbers: ";
88 for (int i = 0; i < size; i++) {
89 std::cin >> array[i];
90 }
91
92 std::cout << "\nEnter the number to be searched: ";
93 std::cin >> key;
94
95 int index = LinearSearch(array, size, key);
96 if (index != -1) {
97 std::cout << "Number found at index: " << index << "\n";
98 } else {
99 std::cout << "Array element not found";
100 }
101 delete[] array;
102 } else {
103 tests(); // run self-test implementations
104 }
105 return 0;
106}
static void tests()
Self-test implementations.
int LinearSearch(int *array, int size, int key)
for IO operations
int main()
Main function.