TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
ternary_search.cpp
Go to the documentation of this file.
1
15#include <iostream>
16
22#define absolutePrecision 10
27#define _target 10
28
29#define MAX 10000000
30
36void get_input() {}
37
48int it_ternary_search(int left, int right, int A[], int target) {
49 while (1) {
50 if (left < right) {
51 if (right - left < absolutePrecision) {
52 for (int i = left; i <= right; i++)
53 if (A[i] == target)
54 return i;
55
56 return -1;
57 }
58
59 int oneThird = (left + right) / 3 + 1;
60 int twoThird = (left + right) * 2 / 3 + 1;
61
62 if (A[oneThird] == target)
63 return oneThird;
64 else if (A[twoThird] == target)
65 return twoThird;
66
67 else if (target > A[twoThird])
68 left = twoThird + 1;
69 else if (target < A[oneThird])
70 right = oneThird - 1;
71
72 else
73 left = oneThird + 1, right = twoThird - 1;
74 } else {
75 return -1;
76 }
77 }
78}
79
90int rec_ternary_search(int left, int right, int A[], int target) {
91 if (left < right) {
92 if (right - left < absolutePrecision) {
93 for (int i = left; i <= right; i++)
94 if (A[i] == target)
95 return i;
96
97 return -1;
98 }
99
100 int oneThird = (left + right) / 3 + 1;
101 int twoThird = (left + right) * 2 / 3 + 1;
102
103 if (A[oneThird] == target)
104 return oneThird;
105 if (A[twoThird] == target)
106 return twoThird;
107
108 if (target < A[oneThird])
109 return rec_ternary_search(left, oneThird - 1, A, target);
110 if (target > A[twoThird])
111 return rec_ternary_search(twoThird + 1, right, A, target);
112
113 return rec_ternary_search(oneThird + 1, twoThird - 1, A, target);
114 } else {
115 return -1;
116 }
117}
118
127void ternary_search(int N, int A[], int target) {
128 std::cout << it_ternary_search(0, N - 1, A, target) << '\t';
129 std::cout << rec_ternary_search(0, N - 1, A, target) << '\t';
130 std::cout << std::endl;
131}
132
134int main() {
135 int N = 21;
136 int A[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 10};
137 get_input();
138 ternary_search(N, A, _target);
139 return 0;
140}
#define _target
void get_input()
int rec_ternary_search(int left, int right, int A[], int target)
#define absolutePrecision
int it_ternary_search(int left, int right, int A[], int target)
int main()
void ternary_search(int N, int A[], int target)