-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearch_in_Rotated_Sorted_Array.cpp
More file actions
98 lines (83 loc) · 1.71 KB
/
Search_in_Rotated_Sorted_Array.cpp
File metadata and controls
98 lines (83 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// Source : https://oj.leetcode.com/problems/search-in-rotated-sorted-array/
// Author : zheng yi xiong
// Date : 2015-01-08
/**********************************************************************************
*
* Suppose a sorted array is rotated at some pivot unknown to you beforehand.
* (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
* You are given a target value to search. If found in the array return its index, otherwise return -1.
* You may assume no duplicate exists in the array.
*
**********************************************************************************/
#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;
class Solution {
public:
int search(int A[], int n, int target) {
int ibegin = 0, iend = n, imid = 0;
while (ibegin != iend)
{
imid = (iend + ibegin) / 2;
if (A[imid] == target)
{
return imid;
}
else if (target < A[imid])
{
if (A[ibegin] < A[imid])
{
if (target >= A[ibegin])
{
iend = imid;
}
else
{
ibegin = imid + 1;
}
}
else
{
iend = imid;
}
}
else
{
if (A[ibegin] < A[imid])
{
ibegin = imid + 1;
}
else
{
if (target >= A[ibegin])
{
iend = imid;
}
else
{
ibegin = imid + 1;
}
}
}
}
return -1;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
int A[] = {4, 5, 6, 7, 0, 1, 2};
int n = 7;
int target = 3;
cout<<"rotated sorted array:\n";
for(int i = 0; i < n; ++i) {
cout<<" "<<A[i];
}
cout<<endl;
cout<<"target value: "<<target<<endl;
Solution so;
int target_index = so.search(A, n, target);
cout<<"target index: "<<target_index<<endl;
system("pause");
return 0;
}