-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFindFixPoint.cs
59 lines (53 loc) · 1.61 KB
/
FindFixPoint.cs
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
namespace DA.Algorithms.Problems
{
public static class FindFixPoint
{
/// <summary>
/// Find fix point in array.
/// Fix point is an index of array in which index and value is the same.
/// <para>Time Complexity - O(n)</para>
/// </summary>
///
/// <returns>
/// Return fix point value/index of the array
/// </returns>
public static int GetFixPoint (int[] array)
{
for (int i = 0; i < array.Length; i++)
if (array[i] == i)
return i;
return -1;
}
/// <summary>
/// Find fix point in sorted array.
/// Fix point is an index of array in which index and value is the same.
/// <para>Time Complexity - O(logn)</para>
/// </summary>
///
/// <param name="array">Sorted array</param>
///
/// <returns>
/// Return fix point value/index of the array
/// </returns>
public static int GetFixPointBinarySearch (int[] array, bool isSorted = false)
{
if (!isSorted)
{
System.Array.Sort (array);
}
int low = 0;
int high = array.Length - 1;
int middle;
while (low <= high)
{
middle = (low + high) / 2;
if (array[middle] == middle)
return middle;
if (array[middle] < middle)
low = middle + 1;
else high = middle - 1;
}
return -1;
}
}
}