Skip to content

Commit

Permalink
Merge pull request Google-Developer-Student-Club-CCOEW#173 from Tanis…
Browse files Browse the repository at this point in the history
…haclippy/search

Search the element
  • Loading branch information
soniadessai authored Oct 16, 2023
2 parents 74473d7 + 7e08c35 commit 271de08
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
23 changes: 23 additions & 0 deletions Search.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
public class Main
{
public static void main(String[] args) {
int arr[]={-5,6,7,12,34};//input array
int target=23;//target element
int low=0;
int high=arr.length-1;
while(low<=high){
int midp=(low+high)/2;
int midnum=arr[midp];
if(target==midnum){
System.out.print(midp); //if element present in the array return the index number
}
else if(midnum<target){
low=midp+1;
}
else{
high=midp-1;
}
}
System.out.print(low); //if the target element not found insert the position it should be placed
}
}
31 changes: 31 additions & 0 deletions searchtarget
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@

class Sol{
public int search(int[]nums,int target){
int low=0; //using binary search
int high=nums.length-1;
while(low<=high){
int midp=(low+high)/2;
int midnum=nums[midp];
if(midnum==target){
return midp;
}
else if(nums[low]<=midnum){
if(nums[low]<=target&&target<midnum){
high=midp-1;
}
else{
low=midp+1;
}
}
else{
if(midnum<=target&&target<nums[high]){
low=midp+1;
}
else{
high=midp-1;
}
}
return -1;//if the target is not found it will return -1;

}
}

0 comments on commit 271de08

Please sign in to comment.