aboutsummaryrefslogtreecommitdiff
path: root/APEX_1.4/common/include/ApexFind.h
blob: 4f490df3a21ebb1879daf2c2deb6297c31de18a4 (plain) (blame)
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
/*
 * Copyright (c) 2008-2017, NVIDIA CORPORATION.  All rights reserved.
 *
 * NVIDIA CORPORATION and its licensors retain all intellectual property
 * and proprietary rights in and to this software, related documentation
 * and any modifications thereto.  Any use, reproduction, disclosure or
 * distribution of this software and related documentation without an express
 * license agreement from NVIDIA CORPORATION is strictly prohibited.
 */


#ifndef APEX_FIND_H
#define APEX_FIND_H

namespace nvidia
{
namespace apex
{
	// binary search
	template<class Sortable>
	int32_t ApexFind(const Sortable* buffer, uint32_t numEntries, const Sortable& element, int (*compare)(const void*, const void*))
	{

#if PX_CHECKED
		if (numEntries > 0)
		{
			for (uint32_t i = 1; i < numEntries; ++i)
			{
				PX_ASSERT(compare(buffer + i - 1, buffer + i) <= 0);
			}
		}
#endif

		int32_t curMin = 0;
		int32_t curMax = (int32_t)numEntries;
		int32_t testIndex = 0;

		while (curMin < curMax)
		{
			testIndex = (curMin + curMax) / 2;
			int32_t compResult = compare(&element, buffer+testIndex);
			if (compResult < 0)
			{
				curMax = testIndex;
			}
			else if (compResult > 0)
			{
				curMin = testIndex;
			}
			else
			{
				return testIndex;
			}

		}

		return -1;
	}

} // namespace apex
} // namespace nvidia

#endif // APEX_FIND_H