Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

binary search 1 #2022

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions SearchInInfiniteSortedArray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Time complexity to O(log(n))
// Space complexity O(1)

public class SearchInInfiniteSortedArray{
public void search(){
int l=0, h = 1;
while(reader.get(h)<target){
l=h;
h = 2 *h;
}
int mid;
while(l<=h){
mid = l + (h-l)/2;
if(reader.get(mid)>target){
h = mid-1;
}
else{
l = mid+1;
}
}

}
}
26 changes: 26 additions & 0 deletions SearchInMatrix.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Time complexity would be log(k) where k = m*n where m is number of rows and n is number of columns.
// space complexity would be O(1).


class SearchInMatrix {
public boolean searchMatrix(int[][] matrix, int target) {
int rows = matrix.length, columns = matrix[0].length;
int l=0, h = (rows* columns)-1;
int m;
while(l<=h){
m = l + (h-l)/2;
int value = matrix[m/columns][m%columns];
if( value == target){
return true;
}
else if(value < target){
l=m+1;
}
else{
h = m-1;
}
}
return false;

}
}
38 changes: 38 additions & 0 deletions SearchInRotatedSortedArray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// time complexity - O(logn) and space complexity - O(1).



public class SearchInRotatedSortedArray {

public int search(int[] nums, int target) {
int l =0, h = nums.length-1;
int mid;
while(l<=h){
mid = l + (h-l)/2;
if(nums[mid] == target){
return mid;
}
else if(nums[mid]>=nums[l]){ // left part is sorted
if(nums[l]<=target && nums[mid]>target){
h = mid-1;
}
else{
l = mid+1;
}
}
else{ //right part is sorted

if(nums[mid]<target && nums[h]>=target){
l = mid+1;
}
else{
h = mid-1;
}

}

}
return -1;

}
}