forked from Google-Developer-Student-Club-CCOEW/Competitive-Programming-2023-GDSC-CUMMINS-X-GDSC-MMCOE
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request Google-Developer-Student-Club-CCOEW#173 from Tanisβ¦
β¦haclippy/search Search the element
- Loading branch information
Showing
2 changed files
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
|
||
} | ||
} |