Skip to content

Commit

Permalink
Merge pull request #79 from yanurag1414/Search-Rotated-Sorted-Array
Browse files Browse the repository at this point in the history
Adding search in rotated sorted array
  • Loading branch information
Chitresh-code authored Oct 24, 2023
2 parents 1a9a2c2 + db3cf41 commit a5215e4
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions DSA_Codesheet/Java/SearchRotatedSorted.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import java.util.Scanner;
public class SearchRotatedSorted {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the size of the rotated sorted array:");
int n = s.nextInt();
System.out.println("Enter the elements of the rotated sorted array:");
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = s.nextInt();
}
System.out.println("Enter the target element to search:");
int target = s.nextInt();
s.close();
searchRotated(arr,n,target);

}
static void searchRotated(int[] arr,int n,int target){
int low = 0;
int high = n-1;
while (low<=high){
int mid = low+(high-low)/2;
if(arr[mid]==target){
System.out.println("Element "+target+" found at "+mid);
return;
}
if(arr[mid]>=arr[low]){
if(target>=arr[low] && target<arr[mid]){
high = mid-1;
}else {
low = mid+1;
}
}else{
if(target>arr[mid] && target<=arr[high]){
low = mid+1;
}else {
high = mid-1;
}
}
}
System.out.println(-1);

}
}

0 comments on commit a5215e4

Please sign in to comment.