How to find the number of times array is rotated in the sorted array by recursion using C#?

CsharpServer Side ProgrammingProgramming

Find index of mid element (minimum element) Apply Binary Search on the subarray based on following conditions −

  • If number lies between start element and element at mid1 position.

  • Then find number in array start to mid-1 using binary search

  • Else if number lies between mid and last element, then find number in array mid to last element using binary search.

Example

 Live Demo

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace ConsoleApplication{
   public class Arrays{
      public int FindNumberRotated(int[] array, int start, int end, int value){
         if (start > end){
            return -1;
         }
         int mid = (start + end) / 2;
         if (array[mid] == value){
            return mid;
         }
         if (array[start] <= array[mid]){
            if (value >= array[start] && value <= array[mid]){
               return FindNumberRotated(array, start, mid - 1, value);
            }
            return FindNumberRotated(array, mid + 1, end, value);
         }
         if (value >= array[mid] && value <= array[end]){
            return FindNumberRotated(array, mid + 1, end, value);
         }
         return FindNumberRotated(array, start, mid - 1, value);
      }
   }
   class Program{
      static void Main(string[] args){
         Arrays a = new Arrays();
         int[] arr = { 3, 4, 5, 6, 7, 8, 9, 10, 1, 2 };
         int res = a.FindNumberRotated(arr, 0, arr.Length - 1, 1);
         Console.WriteLine(res);
      }
   }
}

Output

8
raja
Published on 27-Aug-2021 13:42:47
Advertisements