Skip to content

Commit 579710f

Browse files
committed
First version of binsearch
1 parent 4cc6253 commit 579710f

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

include/cppcore/Common/Sort.h

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,4 +114,24 @@ namespace cppcore {
114114
return true;
115115
}
116116

117+
inline int32_t binSearchImpl(void *key, void *data, size_t num, size_t stride, ComparisonFn func) {
118+
size_t offset = 0;
119+
uint8_t *_data = (uint8_t *)data;
120+
for (size_t i = num; offset < i;) {
121+
size_t idx = (offset + i) / 2;
122+
int32_t result = func(key, &_data[i * stride]);
123+
if (result < 0) {
124+
i = idx;
125+
} else if (result > 0) {
126+
offset = idx + 1;
127+
} else {
128+
return idx;
129+
}
130+
}
131+
return ~offset;
132+
}
133+
134+
int32_t binSearch(int32_t key, int32_t* array, size_t num, ComparisonFn func) {
135+
return binSearchImpl(&key, &array[0], num, sizeof(int32_t), func);
136+
}
117137
} // namespace cppcore

test/common/SortTest.cpp

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,10 @@ TEST_F(SortTest, quicksortTest) {
5656
bool sorted = isSorted(arr, 5, sizeof(int32_t), compDescending<int32_t>);
5757
EXPECT_TRUE(sorted);
5858
}
59+
60+
TEST_F(SortTest, binSearchTest) {
61+
int32_t arr[] = { 1, 2, 3, 5, 4 };
62+
quicksort(arr, 5, sizeof(int32_t), compDescending<int32_t>);
63+
int32_t idx = binSearch(3, arr, 5, compDescending<int32_t>);
64+
EXPECT_EQ(idx, 2);
65+
}

0 commit comments

Comments
 (0)