commit 1abfa416746d13dc9d3885afe9cb4fd532be0b3e Author: Hizenberg Date: Sun Nov 12 19:18:10 2023 +0530 Seaching Algorithms diff --git a/Searching/advanced_binary_search.cpp b/Searching/advanced_binary_search.cpp new file mode 100644 index 0000000..d48ff63 --- /dev/null +++ b/Searching/advanced_binary_search.cpp @@ -0,0 +1,15 @@ +//Advanced Binary Seach. +int max_iter; +double low , high , ans; +double err ; +for(int i = 1 ; i <= max_iter ; i++ ){ + double mid = low + (high - low)/2; + + if( check(mid) ){ + ans = mid; + low = mid + err; + } + else{ + high = mid - err; + } +} \ No newline at end of file diff --git a/Searching/binary_search_jump.cpp b/Searching/binary_search_jump.cpp new file mode 100644 index 0000000..0946d11 --- /dev/null +++ b/Searching/binary_search_jump.cpp @@ -0,0 +1,6 @@ +//Binary Search Jump. +int ans = n; +for(int b = n/2 ; b >= 1 ; b/=2 ){ + while(check(ans - b))ans -= b; +} +cout << ans << endl; \ No newline at end of file diff --git a/Searching/binary_search_normal.cpp b/Searching/binary_search_normal.cpp new file mode 100644 index 0000000..6d33172 --- /dev/null +++ b/Searching/binary_search_normal.cpp @@ -0,0 +1,14 @@ +//Binary Search Normal +int low = 0 , high = n , ans; + +while( low <= high ){ + int mid = low + ( high - low)/2; + + if( check(mid) ){ + ans = mid; + low = mid + 1; + } + else{ + high = mid - 1; + } +} \ No newline at end of file diff --git a/Searching/ternary_search.cpp b/Searching/ternary_search.cpp new file mode 100644 index 0000000..f68dc27 --- /dev/null +++ b/Searching/ternary_search.cpp @@ -0,0 +1,14 @@ +double ternary_search(double l, double r) { + double eps = 1e-9; //set the error limit here + while (r - l > eps) { + double m1 = l + (r - l) / 3; + double m2 = r - (r - l) / 3; + double f1 = f(m1); //evaluates the function at m1 + double f2 = f(m2); //evaluates the function at m2 + if (f1 < f2) + l = m1; + else + r = m2; + } + return f(l); //return the maximum of f(x) in [l, r] +} \ No newline at end of file