HyperDbg/hyperdbg/include/components/optimizations/code/BinarySearch.c

74 lines
1.4 KiB
C
Raw Permalink Normal View History

2023-07-28 19:13:16 +09:00
/**
* @file BinarySearch.c
2023-08-21 13:40:37 +09:00
* @author Mohammad K. Fallah (mkf1980@gmail.com)
* @brief The file contains array management routines (Binary Search)
2023-07-28 19:13:16 +09:00
* @details
2023-08-20 22:41:47 +09:00
* @version 0.5
2023-07-28 19:13:16 +09:00
* @date 2023-07-28
*
* @copyright This project is released under the GNU Public License v3.
*
*/
#include "pch.h"
/**
* @brief A utility function to print an array of size NumberOfItems
*
* @param ArrayPtr
* @param NumberOfItems
*
* @return VOID
*/
VOID
2023-08-21 20:06:34 +09:00
BinarySearchPrintArray(UINT64 ArrayPtr[], UINT32 NumberOfItems)
2023-07-28 19:13:16 +09:00
{
2023-07-31 17:44:41 +09:00
UINT32 i;
2023-07-28 19:13:16 +09:00
for (i = 0; i < NumberOfItems; i++)
2023-07-31 17:44:41 +09:00
{
Log("%llx ", ArrayPtr[i]);
}
2023-07-28 19:13:16 +09:00
Log("\n");
}
/**
* @brief A utility function to perform the binary search
*
* @param ArrayPtr
2023-07-31 17:44:41 +09:00
* @param NumberOfItems
* @param ResultIndex
* @param Key
2023-07-28 19:13:16 +09:00
*
2023-07-31 17:44:41 +09:00
* @return BOOLEAN
2023-07-28 19:13:16 +09:00
*/
2023-07-31 17:44:41 +09:00
BOOLEAN
2023-08-21 20:06:34 +09:00
BinarySearchPerformSearchItem(UINT64 ArrayPtr[], UINT32 NumberOfItems, UINT32 * ResultIndex, UINT64 Key)
2023-07-28 19:13:16 +09:00
{
UINT32 Position = 0;
UINT32 Limit = NumberOfItems;
2023-07-31 17:44:41 +09:00
while (Position < Limit)
{
UINT32 TestPos = Position + ((Limit - Position) >> 1);
if (ArrayPtr[TestPos] < Key)
Position = TestPos + 1;
2023-07-28 19:13:16 +09:00
else
Limit = TestPos;
2023-07-28 19:13:16 +09:00
}
2023-08-03 18:46:51 +09:00
if (Position < NumberOfItems && ArrayPtr[Position] == Key)
{
//
// Set the result position in the array
//
*ResultIndex = Position;
return TRUE;
}
else
{
return FALSE;
}
2023-07-28 19:13:16 +09:00
}