- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to find the number of times array is rotated in the sorted array by recursion using C#?
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
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
Advertisements