Skip to content

Commit db149bf

Browse files
fix: fix overflow check in data_structures/list_array.cpp (TheAlgorithms#1983)
* fix(list_array): fix overflow check + use template for list size * Update data_structures/list_array.cpp Co-authored-by: David Leal <halfpacho@gmail.com> Co-authored-by: David Leal <halfpacho@gmail.com>
1 parent 4b7982a commit db149bf

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed

data_structures/list_array.cpp

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,9 @@ namespace list_array {
2929
/**
3030
* @brief Structure of List with supporting methods.
3131
*/
32+
template <uint64_t N>
3233
struct list {
33-
std::array<uint64_t, 50> data{}; // Array that implement list
34+
std::array<uint64_t, N> data{}; // Array that implement list
3435
uint64_t top = 0; // Pointer to the last element
3536
bool isSorted = false; // indicator whether list is sorted or not
3637
/**
@@ -41,7 +42,7 @@ namespace list_array {
4142
* @param val element that will be searched
4243
* @return index of element in the list if present else -1
4344
*/
44-
uint64_t BinarySearch(const std::array<uint64_t, 50> &dataArr, const uint64_t &first, const uint64_t &last,
45+
uint64_t BinarySearch(const std::array<uint64_t, N> &dataArr, const uint64_t &first, const uint64_t &last,
4546
const uint64_t &val) {
4647
// If both pointer cross each other means no element present in the list which is equal to the val
4748
if (last < first) {
@@ -68,7 +69,7 @@ namespace list_array {
6869
* @param val element that will be searched
6970
* @return index of element in the list if present else -1
7071
*/
71-
uint64_t LinearSearch(const std::array<uint64_t, 50> &dataArr, const uint64_t &val) const {
72+
uint64_t LinearSearch(const std::array<uint64_t, N> &dataArr, const uint64_t &val) const {
7273
// Going through each element in the list
7374
for (uint64_t i = 0; i < top; i++) {
7475
if (dataArr[i] == val) {
@@ -131,7 +132,7 @@ namespace list_array {
131132
*/
132133
void insert(const uint64_t &val) {
133134
// overflow check
134-
if (top == 49) {
135+
if (top == N) {
135136
std::cout << "\nOverflow";
136137
return;
137138
}
@@ -203,7 +204,7 @@ namespace list_array {
203204
* @returns void
204205
*/
205206
static void test() {
206-
data_structures::list_array::list L;
207+
data_structures::list_array::list<50> L;
207208

208209
// Insert testing
209210
L.insert(11);

0 commit comments

Comments
 (0)