How to Find Element in Rotated Sorted Array?

In this article, we are going to find the element in a rotated sorted array using the programs in different computer languages like Java and C++. We are going to use different approaches to find the element in rotated sorted array. We are also going to find the Time complexity and the Space complexity of the program.

Finding the pivot point, splitting the array into two smaller arrays, and running a binary search are the intended steps.

The key concept for locating a pivot is:

  • In an array that has been rotated and sorted (in increasing order), the pivot element is the only one for which the element after it is smaller.
  • Pivot can be located via binary search, which is based on the previous concept.
  • The element at l will obviously be larger than the element at mid if rotation has occurred in the left half of the search space for indices in the range [l, r] where the middle index is mid.
  • The left half will be sorted without it, but the element at mid will be larger than the element at r.
  • Subdivide the array into two when the pivot has been located.

Every sub-array has been sorted now so that binary search can be used to find an element.

Implementation of the Program

The following steps are used to implement the program. The goal is to locate the key within an N-dimensional, sorted, and rotated array called arr[].

  • Utilize binary search to determine the pivot point. The initial array index will be low, while the last array index will be high.
  • We will determine the midpoint based on the high and low values.
  • Return the value at mid-1 as the pivot if it exceeds the value at mid.
  • Otherwise, return the mid-value as the pivot if the value at the mid+1 is smaller than the mid.
  • Consider the left half instead if the value at the low position is higher than the value at the mid position. If not, think about the right half.
  • Using the discovered pivot as a guide, divide the array into two smaller arrays.
  • One of the two sub-arrays should now be called using binary search.
  • Search in the left array if the element is greater than the 0th element.
  • If not, look in the appropriate array.
  • Return the index if the element can be found in the chosen sub-array.
  • Return -1 if not.

Example:

#include <bits/stdc++.h>
using namespace std;
// Standard Binary Search function
int binarySearch(int arr[], int low, int high, int key)
{
    if (high < low)
        return -1;


    int mid = (low + high) / 2;
    if (key == arr[mid])
        return mid;


    if (key > arr[mid])
        return binarySearch(arr, (mid + 1), high, key);


    return binarySearch(arr, low, (mid - 1), key);
}
int findPivot(int arr[], int low, int high)
{
    // Base cases
    if (high < low)
        return -1;
    if (high == low)
        return low;


    int mid = (low + high) / 2;
    if (mid < high && arr[mid] > arr[mid + 1])
        return mid;


    if (mid > low && arr[mid] < arr[mid - 1])
        return (mid - 1);


    if (arr[low] >= arr[mid])
        return findPivot(arr, low, mid - 1);


    return findPivot(arr, mid + 1, high);
}


int pivotedBinarySearch(int arr[], int n, int key)
{
    int pivot = findPivot(arr, 0, n - 1);


    // If we didn't find a pivot,
    // then array is not rotated at all
    if (pivot == -1)
        return binarySearch(arr, 0, n - 1, key);


    // If we found a pivot, then first compare with pivot
    // and then search in two subarrays around pivot
    if (arr[pivot] == key)
        return pivot;


    if (arr[0] <= key)
        return binarySearch(arr, 0, pivot - 1, key);


    return binarySearch(arr, pivot + 1, n - 1, key);
}


// Driver program to check above functions
int main()
{


    int arr1[] = { 5, 6, 7, 8, 9, 10, 1, 2, 3 };
    int n = sizeof(arr1) / sizeof(arr1[0]);
    int key = 3;


    cout << "Index of the element is : "
<< pivotedBinarySearch(arr1, n, key);


    return 0;
}

Output:

Index of the element is : 8

Time complexity of the following program is - O(log N)

The Space complexity of the following program is - O(1)


Related Topics

How to find archived emails in Gmail

How to find archived emails in Gmail Similar/Related Questions Where do Gmail archived emails go? How can Gmail users access archived emails? How to get to archived Gmail? In which folder does the archived Gmail...

4 minutes read.

How to snooze an email in Gmail

How to snooze an email in Gmail With the popularity of Gmail, today every deal is likely to be discussed in emails. And with so many things rushing in the Inbox,...

3 minutes read.

How to Find Divisors of a Number?

A number that equally divides a larger integer is referred to as a divisor or factor. By simply listing all the possible methods to multiply two numbers together to obtain...

3 minutes read.

How to write a cover letter

How to write a cover letter The letter that you include with your job application is known as a cover letter. One is suggested to always include a cover letter with your job application...

5 minutes read.

How to write a cheque?

How to write a cheque? In today's time, digital payments are consistently gaining more market share, but it's also important to know how to write a cheque. Many companies, employers, workers, and landlords still...

2 minutes read.

How to block emails on Gmail?

How to block emails on Gmail? Email or electronic mail is shared on the internet, including content, website URL, signature and different forms of attachments (unlike images, mp4, mp3, Pdf, excel,...

7 minutes read.

How to Find Connected Components in Graph

In this article, we are going to find connected components in a graph by building a program in C++ language. We are going to use different approaches to build the...

4 minutes read.

How to mark all emails as read in Gmail?

How to mark all emails as read in Gmail Gmail is extensively used to exchange official documents, expressions, proposals around the world. In the business industry leaving unread mails is considered...

3 minutes read.

How to delete Gmail Account?

What is Gmail? Gmail is a free mobile and web-based email service introduced by Google on April 1, 2004. Gmail is used for personal to business purposes. It allows users to...

2 minutes read.

How to delete a page in Microsoft Word?

What is Microsoft Word? Microsoft word is a word processing program, which is developed by Microsoft. It was initially launched on 25 October 1983 and has since been modified many times. Generally, Microsoft Word...

2 minutes read.

How to Cancel Netflix

How to Cancel Netflix Netflix Netflix is a service that lets its members watch a variety of television shows, movies, documentaries, and web series who purchase its subscription. You can enjoy unlimited ad-free...

3 minutes read.

How to accelerate the speed of loading images on any website?

No website can be successful without attractive and relevant images or pictures. In the current time, the users want speedy information about their searches on the internet browser. The image...

3 minutes read.

How to convert epoch date to time?

How to convert epoch date to time? The concept of the epoch is vital for computation purposes. Epoch is nothing but the total milliseconds passed from 1st January 1970. This concept...

3 minutes read.

How to address a letter (formal and in-formal)

How to address a letter In the generation of (SMS) and emails, it is still necessary to know how to address a letter for the one. Throughout the modern world, formal letters are...

7 minutes read.

How to Create a Group Email in Gmail

How to Create a Group Email in Gmail Every now and then, one needs to pass on or share a message to several people at the same time. To make this...

6 minutes read.

How to take a screenshot on windows

How to take a screenshot on windows A screenshot is a picture taken on your computer. In this section, we will learn how to take screenshot on windows operating system. We can take screenshot...

5 minutes read.

Does my computer have Bluetooth?

Does my computer have Bluetooth? With the advancement of IOT (Internet of things) and high-tech electronic gadgets, Bluetooth has become perennial in our digital lives. Most of us are already familiar...

6 minutes read.

How To Connect Air pods To Computer?

How To Connect Air pods To Computer Apple has put light on a statement and said that it believes the future is wireless. This technology is pacing up with the time,...

5 minutes read.

How to add Signature to your Mail

How to add Signature to your Mail Gmail has formed an inevitable aura around the business world. Gmail was launched in the year 2004 as an email service provider with very...

7 minutes read.

How to Multiply Fractions?

What is a Fraction? A fraction is a number that divides a whole number into equal parts. A fraction tells us how many parts we have from the whole part. We...

2 minutes read.