Skip to content

Commit

Permalink
binary search; lower bound; upper bound
Browse files Browse the repository at this point in the history
  • Loading branch information
Nanashii76 authored Feb 28, 2024
1 parent 85c8f8a commit 98b28f0
Show file tree
Hide file tree
Showing 2 changed files with 170 additions and 0 deletions.
41 changes: 41 additions & 0 deletions theory/search_algorithm/binary_search.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#include <iostream>

int binary_search(int arr[], int l, int r, int x) {

while(l <= r) {
int mid = (l+r)/2;

if(arr[mid] < x)
l=mid+1;
else if(arr[mid] > x)
r=mid-1;
else
return mid;

}

return EXIT_FAILURE;

}

int main(){

int arr[] = {1,2,3,4,5,6,7,8,9,10};
int n = 10;
if(binary_search(arr,0,n-1,6) != EXIT_FAILURE)
std::cout << "Element found at position: " << binary_search(arr,0,n-1,6) << std::endl;
else
std::cout << "Not-Found" << std::endl;


}










129 changes: 129 additions & 0 deletions theory/search_algorithm/frequency_count.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
#include <iostream>
#include <vector>

// The most otimized solution
/*
We've to program 2 functions
-> lower bound
-> upper bound
to get the first occurency of the number and the last, the
answer'll be (Lo-Fo+1)
*/

int lower_bound(std::vector<int> arr, int key) {

int l = 0;
int r = arr.size() - 1;

int ans = -1;
while( l <= r) {

int mid = (l+r)/2;

if(arr[mid]==key) {
ans = mid;
r = mid - 1;
} else if (arr[mid] > key)
r=mid-1;
else
l=mid+1;

}

return ans;


}

int upper_bound(std::vector<int> arr, int key) {

int l = 0;
int r = arr.size() - 1;

int ans = -1;
while( l <= r) {

int mid = (l+r)/2;

if(arr[mid]==key) {
ans = mid;
l = mid + 1;
} else if (arr[mid] > key)
r=mid-1;
else
l=mid+1;

}

return ans;


}

int main(){

std::vector<int> arr = {0,1,1,1,1,2,2,2,3,4,4,5,10};
std::cout << (upper_bound(arr,1)-lower_bound(arr,1))+1 << std::endl;

}


//My solution
/*
int binary_search(int arr[], int l, int r, int x) {
while(l <= r) {
int mid = (l+r)/2;
if(arr[mid] < x)
l=mid+1;
else if(arr[mid] > x)
r=mid-1;
else
return mid;
}
return -1;
}
int main(){
int arr[] = {0,1,1,1,1,2,2,2,3,4,4,5,10};
int size = 12;
int id = binary_search(arr,0,size-1,2);
int i = id;
int count = 0;
if(id != -1) {
while(arr[i] == arr[id]) {
count++;
i++;
}
}
std::cout << count << std::endl;
}
*/











0 comments on commit 98b28f0

Please sign in to comment.