Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,913 questions

51,845 answers

573 users

How to search for an element in circular sorted integer array with Java

1 Answer

0 votes
public class MyClass {
    private static int searchCircularSortedArray(int[] arr, int element) {
    	int low = 0;
    	int high = arr.length - 1;
    
    	while (low <= high) {
    		int mid = (low + high) / 2;
    
    		if (element == arr[mid]) {
    			return mid;
    		}
    
    		if (arr[mid] <= arr[high]) {
    			if (element > arr[mid] && element <= arr[high]) {
    				low = mid + 1; // search the right sorted half
    			}
    			else {
    				high = mid - 1; // search the left side
    			}
    		}
    		else {
    			if (element >= arr[low] && element < arr[mid]) {
    				high = mid - 1; // search the left sorted half
    			}
    			else {
    				low = mid + 1; // search the right side
    			}
    		}
    	}
    
    	return -1;
    }
    
    public static void main(String args[]) {
      	int[] array = {6, 9, 10, 13, 2, 3, 5, 6, 8};
	    int element = 5;

	    int index = searchCircularSortedArray(array, element);

	    if (index != -1) {
		    System.out.print("index = " + index);
	    }
	    else {
		    System.out.print("Element not found");
	    }
    }
}




/*
run:
     
index = 6

*/

 



answered Nov 23, 2023 by avibootz
...