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,914 questions

51,847 answers

573 users

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

1 Answer

0 votes
#include <iostream>

int searchCircularSortedArray(int arr[], int size, int element) {
    int low = 0, high = size - 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;
}
 
int main()
{
    int array[] = {6, 9, 10, 13, 2, 3, 5, 6, 8};
    int element = 5;
 
    int size = sizeof(array) / sizeof(array[0]);
    int index = searchCircularSortedArray(array, size, element);
 
    if (index != -1) {
        std::cout << "index = " << index;
    }
    else {
        std::cout << "Element not found";
    }
 
    return 0;
}
    
    
    
    
/*
run:
     
index = 6

*/

 



answered Nov 23, 2023 by avibootz
...