From fc2f279a9344c31232275103c485d5c6335635ea Mon Sep 17 00:00:00 2001 From: Justsvetoslavov Date: Tue, 16 Nov 2021 16:56:56 +0200 Subject: Added solutions Pract.05 --- pract_SI/Pract. 05/Solutions/task6.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 pract_SI/Pract. 05/Solutions/task6.cpp (limited to 'pract_SI/Pract. 05/Solutions/task6.cpp') diff --git a/pract_SI/Pract. 05/Solutions/task6.cpp b/pract_SI/Pract. 05/Solutions/task6.cpp new file mode 100644 index 0000000..a3804fc --- /dev/null +++ b/pract_SI/Pract. 05/Solutions/task6.cpp @@ -0,0 +1,26 @@ +/* +A iterative binary search function. +It returns location of x in given array arr[l..r] if present, +otherwise -1. +*/ + +//int l - left side index +//int r - right side index +//int m - middle index +//int x - number 'x' we are searching for + +int binarySearch1(int *arr, int l, int r, int x) +{ + while (l <= r) + { + int m = l + (r - l) / 2; + if (arr[m] == x)// Check if x is present at mid + return m; + if (arr[m] < x)// If x greater, ignore left half + l = m + 1; + else + r = m - 1; // If x is smaller, ignore right half + } + + return -1; // if we reach here, then the element was not present +} \ No newline at end of file -- cgit v1.3.1-23-gd82d