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



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

    1. If the number lies between the start element and the element at the mid1 position.
    2. Then find a number in array start to mid-1 using binary search
    3. Else if the number lies between mid and last element, then find a number in array mid to last element using binary search.

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace CsharpCode_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 Csharp_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);
      }
   }
}

0 Comment's

Comment Form

Submit Comment