1
+ def search (arr , target ):
2
+ left , right = 0 , len (arr ) - 1
3
+
4
+ while left <= right :
5
+ mid = left + (right - left ) // 2
6
+
7
+ # Check if the target is at mid
8
+ if arr [mid ] == target :
9
+ return True
10
+
11
+ # Handle duplicates by shrinking the search space
12
+ if arr [left ] == arr [mid ] == arr [right ]:
13
+ left += 1
14
+ right -= 1
15
+ # Left half is sorted
16
+ elif arr [left ] <= arr [mid ]:
17
+ # Check if target is in the left sorted portion
18
+ if arr [left ] <= target < arr [mid ]:
19
+ right = mid - 1
20
+ else :
21
+ left = mid + 1
22
+ # Right half is sorted
23
+ else :
24
+ # Check if target is in the right sorted portion
25
+ if arr [mid ] < target <= arr [right ]:
26
+ left = mid + 1
27
+ else :
28
+ right = mid - 1
29
+
30
+ # If target is not found
31
+ return False
32
+
33
+
34
+
35
+ # Time Complexity = O(n)
36
+ # Space Complexity = O(1)
37
+
38
+
39
+
40
+ ##################################################################
41
+
42
+
43
+
44
+ # Driver code
45
+ def test_search ():
46
+ test_cases = [
47
+ ([47 , 78 , 90 , 901 , 10 , 30 , 40 , 42 , 42 ], 30 , True ),
48
+ ([47 , 78 , 90 , 901 , 10 , 30 , 40 , 42 , 42 ], 100 , False ),
49
+ ([4 , 5 , 6 , 7 , 0 , 1 , 2 ], 0 , True ),
50
+ ([4 , 5 , 6 , 7 , 0 , 1 , 2 ], 3 , False ),
51
+ ([1 , 1 , 3 , 3 , 3 , 3 , 1 ], 1 , True ),
52
+ ([1 , 1 , 1 , 3 , 3 , 3 ], 3 , True ),
53
+ ([5 , 6 , 7 , 1 , 2 , 3 , 4 ], 6 , True ),
54
+ ([5 , 6 , 7 , 1 , 2 , 3 , 4 ], 8 , False ),
55
+ ([1 ], 1 , True ),
56
+ ([2 ], 1 , False )
57
+ ]
58
+
59
+ for i , (arr , target , expected ) in enumerate (test_cases ):
60
+ result = search (arr , target )
61
+ assert result == expected , f"Test case { i + 1 } failed: expected { expected } , got { result } "
62
+ print (f"Test case { i + 1 } passed!" )
63
+
64
+ # Run the test cases
65
+ test_search ()
0 commit comments