Added binarySearch, and isSorted functions.

This commit is contained in:
Бранимир Караџић
2022-08-07 19:26:28 -07:00
parent 74b5b7ef11
commit 81025f36da
3 changed files with 127 additions and 10 deletions

View File

@@ -18,19 +18,45 @@ TEST_CASE("quickSort", "")
"jagoda",
};
bx::quickSort(str, BX_COUNTOF(str), sizeof(void*)
, [](const void* _lhs, const void* _rhs)
auto strCmpFn = [](const void* _lhs, const void* _rhs)
{
const char* lhs = *(const char**)_lhs;
const char* rhs = *(const char**)_rhs;
return bx::strCmp(lhs, rhs);
});
};
REQUIRE(!bx::isSorted(str, BX_COUNTOF(str), sizeof(str[0]), strCmpFn) );
bx::quickSort(str, BX_COUNTOF(str), sizeof(str[0]), strCmpFn);
REQUIRE(0 == bx::strCmp(str[0], "jabuka") );
REQUIRE(0 == bx::strCmp(str[1], "jagoda") );
REQUIRE(0 == bx::strCmp(str[2], "kruska") );
REQUIRE(0 == bx::strCmp(str[3], "malina") );
REQUIRE(bx::isSorted(str, BX_COUNTOF(str), sizeof(str[0]), strCmpFn) );
auto bsearchStrCmpFn = [](const void* _lhs, const void* _rhs)
{
const char* lhs = (const char*)_lhs;
const char* rhs = *(const char**)_rhs;
return bx::strCmp(lhs, rhs);
};
REQUIRE(-1 == bx::binarySearch("sljiva", str, BX_COUNTOF(str), sizeof(str[0]), bsearchStrCmpFn) );
REQUIRE( 0 == bx::binarySearch("jabuka", str, BX_COUNTOF(str), sizeof(str[0]), bsearchStrCmpFn) );
REQUIRE( 1 == bx::binarySearch("jagoda", str, BX_COUNTOF(str), sizeof(str[0]), bsearchStrCmpFn) );
REQUIRE( 2 == bx::binarySearch("kruska", str, BX_COUNTOF(str), sizeof(str[0]), bsearchStrCmpFn) );
REQUIRE( 3 == bx::binarySearch("malina", str, BX_COUNTOF(str), sizeof(str[0]), bsearchStrCmpFn) );
REQUIRE(-1 == bx::binarySearch("kupina", str, BX_COUNTOF(str), sizeof(str[0]), bsearchStrCmpFn) );
auto byteCmpFn = [](const void* _lhs, const void* _rhs)
{
int8_t lhs = *(const int8_t*)_lhs;
int8_t rhs = *(const int8_t*)_rhs;
return lhs - rhs;
};
int8_t byte[128];
bx::RngMwc rng;
for (uint32_t ii = 0; ii < BX_COUNTOF(byte); ++ii)
@@ -38,16 +64,14 @@ TEST_CASE("quickSort", "")
byte[ii] = rng.gen()&0xff;
}
bx::quickSort(byte, BX_COUNTOF(byte), 1
, [](const void* _lhs, const void* _rhs)
{
int8_t lhs = *(const int8_t*)_lhs;
int8_t rhs = *(const int8_t*)_rhs;
return lhs - rhs;
});
REQUIRE(!bx::isSorted(byte, BX_COUNTOF(byte), sizeof(byte[0]), byteCmpFn) );
bx::quickSort(byte, BX_COUNTOF(byte), sizeof(byte[0]), byteCmpFn);
for (uint32_t ii = 1; ii < BX_COUNTOF(byte); ++ii)
{
REQUIRE(byte[ii-1] <= byte[ii]);
}
REQUIRE(bx::isSorted(byte, BX_COUNTOF(byte), sizeof(byte[0]), byteCmpFn) );
}