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
9
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 delete[] array;
49
50 size = 6;
51 array = new int[size];
52 for (int i = 0; i < size; i++) {
53 array[i] = i;
54 }
55
56 assert(LinearSearch(array, size, 3) == 3);
57 assert(LinearSearch(array, size, 1) == 1);
58 assert(LinearSearch(array, size, 5) == 5);
59
60 std::cout << "All tests have successfully passed!\n";
61 delete[] array; // free memory up
62}
63
68int main() {
69 int mode = 0;
70
71 std::cout << "Choose mode\n";
72 std::cout << "Self-test mode (1), interactive mode (2): ";
73
74 std::cin >> mode;
75
76 if (mode == 2) {
77 int size = 0;
78 std::cout << "\nEnter the size of the array [in range 1-30 ]: ";
79 std::cin >> size;
80
81 while (size <= 0 || size > 30) {
82 std::cout << "Size can only be 1-30. Please choose another value: ";
83 std::cin >> size;
84 }
85
86 int *array = new int[size];
87 int key = 0;
88
89 // Input for the array elements
90 std::cout << "Enter the array of " << size << " numbers: ";
91 for (int i = 0; i < size; i++) {
92 std::cin >> array[i];
93 }
94
95 std::cout << "\nEnter the number to be searched: ";
96 std::cin >> key;
97
98 int index = LinearSearch(array, size, key);
99 if (index != -1) {
100 std::cout << "Number found at index: " << index << "\n";
101 } else {
102 std::cout << "Array element not found";
103 }
104 delete[] array;
105 } else {
106 tests(); // run self-test implementations
107 }
108 return 0;
109}
static void tests()
Self-test implementations.
int LinearSearch(int *array, int size, int key)
for IO operations
int main()
Main function.