Guest User

Untitled

a guest
Feb 17th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. using System;
  2.  
  3. //if lo >mid -> pivot is on the right
  4. // if hi <mid -> pivot is on the left;
  5.  
  6. //Case 1 :- pivot on right hi < mid -> and lo <num <mid :- hi = mid-1;
  7. //case 2 :- else of case 1 :- lo = mid +1
  8.  
  9. //case 3 :- pivot on left end :- lo > mid :- and mid < num < hi :- lo = mid+1
  10. //case 4 :- else of case 1 :- hi= mid-1;
  11.  
  12. // [1,2] :- 2
  13.  
  14. // mid - a[0] -> 1
  15.  
  16. class Solution
  17. {
  18. public static int ShiftedArrSearch(int[] shiftArr, int num)
  19. {
  20. // your code goes here
  21. if(shiftArr ==null || shiftArr.Length==0)
  22. return -1;
  23.  
  24. int lo=0, hi= shiftArr.Length-1;
  25.  
  26. while(lo<=hi)
  27. {
  28. int mid = lo + (hi-lo)/2;
  29. int middleValue = shiftArr[mid];
  30. int highValue = shiftArr[hi];
  31.  
  32. if(middleValue == num)
  33. return mid;
  34.  
  35. if(highValue < middleValue) //case 1 and 2 ?
  36. {
  37. // left half ascending
  38. if(shiftArr[lo] <= num && middleValue > num)
  39. hi=mid-1;
  40. else
  41. lo= mid +1;
  42.  
  43. }
  44. else
  45. {
  46. if(shiftArr[hi] >= num && middleValue < num)
  47. lo=mid+1;
  48. else
  49. hi=mid-1;
  50. }
  51. }
  52.  
  53. return -1;
  54. }
  55.  
  56. static void Main(string[] args)
  57. {
  58. int[] arr = new int[]{1,2};
  59. Console.WriteLine(ShiftedArrSearch(arr, 2));
  60. }
  61. }
Add Comment
Please, Sign In to add comment