diff --git a/snippets/algorithm/.cph/.binary_search.cpp_94210d3de490345f43ef2720fb462aa4.prob b/snippets/algorithm/.cph/.binary_search.cpp_94210d3de490345f43ef2720fb462aa4.prob new file mode 100644 index 00000000..c6b192cd --- /dev/null +++ b/snippets/algorithm/.cph/.binary_search.cpp_94210d3de490345f43ef2720fb462aa4.prob @@ -0,0 +1 @@ +{"name":"Local: binary_search","url":"c:\\Users\\mukun\\OneDrive\\Documents\\GitHub\\30-seconds-of-cpp\\snippets\\algorithm\\binary_search.cpp","tests":[{"id":1664613834669,"input":"","output":""}],"interactive":false,"memoryLimit":1024,"timeLimit":3000,"srcPath":"c:\\Users\\mukun\\OneDrive\\Documents\\GitHub\\30-seconds-of-cpp\\snippets\\algorithm\\binary_search.cpp","group":"local","local":true} \ No newline at end of file diff --git a/snippets/algorithm/binary_search.cpp b/snippets/algorithm/binary_search.cpp new file mode 100644 index 00000000..9393cf95 --- /dev/null +++ b/snippets/algorithm/binary_search.cpp @@ -0,0 +1,49 @@ +/* + Author : Mukund Ladani + Date : Date format 10/01/2022 + Time : Time format 14:01 + Description : Performed Binary Search. Along with proto-type of array. +*/ + +#include + +template +bool binary_search(ForwardIt first, ForwardIt last, const T &value) +{ + first = std::lower_bound(first, last, value); + return (!(first == last) && !(value < *first)); +} + +void show(int a[], int arraysize) +{ + for (int i = 0; i < arraysize; ++i) + { + std::cout << a[i] << " "; + } +} + +int main() +{ + int a[] = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0}; + int asize = sizeof(a) / sizeof(a[0]); + std::cout << "\n The array is : "; + show(a, asize); + std::cout << "\n\nLet's say we want to search for 2 in the array"; + std::cout << "\n So, we first sort the array"; + std::sort(a, a + asize); + std::cout << "\n\n The array after sorting is : "; + show(a, asize); + std::cout << "\n\nNow, we do the binary search"; + if (std::binary_search(a, a + 10, 2)) + std::cout << "\nElement found in the array"; + else + std::cout << "\nElement not found in the array"; + + std::cout << "\n\nNow, say we want to search for 10"; + if (std::binary_search(a, a + 10, 10)) + std::cout << "\nElement found in the array"; + else + std::cout << "\nElement not found in the array"; + + return 0; +} \ No newline at end of file