Linear search algorithm
More...
#include <iostream>
#include <cassert>
◆ LinearSearch()
int LinearSearch |
( |
int * |
array, |
|
|
int |
size, |
|
|
int |
key |
|
) |
| |
for assert
for IO operations
[Algorithm implementation for linear search]
- Parameters
-
[in] | array | array to search in |
[in] | size | length of array |
[in] | key | key value to search for |
- Returns
- index where the key-value occurs in the array
-
-1 if key-value not found
22{
23 for (int i = 0; i < size; ++i)
24 {
25 if (array[i] == key) {
26 return i;
27 }
28 }
29
30
31 return -1;
32}
◆ main()
Main function.
- Returns
- 0 on exit
66 {
67 int mode = 0;
68
70 std::cout <<
"Self-test mode (1), interactive mode (2): ";
71
73
74 if (mode == 2) {
75 int size = 0;
76 std::cout <<
"\nEnter the size of the array: ";
78
79 while ((size <= 1) || (size >= 30)) {
80 std::cout <<
"Size cannot be less than zero. Please choose another value: ";
82 }
83
84 int *array = new int[size];
85 int key = 0;
86
87
88 std::cout <<
"Enter the array of " << size <<
" numbers: ";
89 for (int i = 0; i < size; i++) {
91 }
92
93 std::cout <<
"\nEnter the number to be searched: ";
95
97 if (index != -1)
98 {
99 std::cout <<
"Number found at index: " << index <<
"\n";
100 }
101 else
102 {
104 }
105 delete[] array;
106 }
107 else {
109 }
110 return 0;
111}
static void tests()
Self-test implementations.
Definition: linear_search.cpp:38
int LinearSearch(int *array, int size, int key)
for assert
Definition: linear_search.cpp:21
◆ tests()
Self-test implementations.
- Returns
- void
38 {
39 int size = 4;
40 int *array = new int[size];
41 for (int i = 0; i < size; i++) {
42 array[i] = i;
43 }
44
48
49 size = 6;
50 for (int i = 0; i < size; i++) {
51 array[i] = i;
52 }
53
57
58 std::cout <<
"All tests have successfully passed!\n";
59 delete[] array;
60}