Linear search algorithm
More...
#include <cassert>
#include <iostream>
|
int | LinearSearch (int *array, int size, int key) |
| for IO operations
|
|
static void | tests () |
| Self-test implementations.
|
|
int | main () |
| Main function.
|
|
◆ LinearSearch()
int LinearSearch |
( |
int * | array, |
|
|
int | size, |
|
|
int | key ) |
for IO operations
for assert
[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
21 {
22 for (int i = 0; i < size; ++i) {
23 if (array[i] == key) {
24 return i;
25 }
26 }
27
28
29
30 return -1;
31}
◆ main()
Main function.
- Returns
- 0 on exit
65 {
66 int mode = 0;
67
69 std::cout <<
"Self-test mode (1), interactive mode (2): ";
70
72
73 if (mode == 2) {
74 int size = 0;
75 std::cout <<
"\nEnter the size of the array [in range 1-30 ]: ";
77
78 while (size <= 0 || size > 30) {
79 std::cout <<
"Size can only be 1-30. Please choose another value: ";
81 }
82
83 int *array = new int[size];
84 int key = 0;
85
86
87 std::cout <<
"Enter the array of " << size <<
" numbers: ";
88 for (int i = 0; i < size; i++) {
90 }
91
92 std::cout <<
"\nEnter the number to be searched: ";
94
96 if (index != -1) {
97 std::cout <<
"Number found at index: " << index <<
"\n";
98 } else {
100 }
101 delete[] array;
102 } else {
104 }
105 return 0;
106}
static void tests()
Self-test implementations.
Definition linear_search.cpp:37
int LinearSearch(int *array, int size, int key)
for IO operations
Definition linear_search.cpp:21
◆ tests()
Self-test implementations.
- Returns
- void
37 {
38 int size = 4;
39 int *array = new int[size];
40 for (int i = 0; i < size; i++) {
41 array[i] = i;
42 }
43
47
48 size = 6;
49 for (int i = 0; i < size; i++) {
50 array[i] = i;
51 }
52
56
57 std::cout <<
"All tests have successfully passed!\n";
58 delete[] array;
59}