-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearch01List.cs
More file actions
53 lines (48 loc) · 1.62 KB
/
Search01List.cs
File metadata and controls
53 lines (48 loc) · 1.62 KB
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
using System;
using System.Collections.Generic;
namespace DA.Algorithms.Problems
{
public static class Search01List
{
/// <summary>
/// Find the index of the first 1 in given list of 0's and 1's in which all the 0's come before 1's.
/// <para>Time Complexity - O(logn)</para>
/// </summary>
///
/// <exception cref="System.ArgumentNullException"/>
///
/// <returns>
/// Return index of the first 1 in given list is so exists, otherwise return -1.
/// </returns>
public static int BinarySearch01 (int[] array)
{
if (array == null) throw new System.ArgumentNullException ();
if (array.Length == 1 && array[0] == 1) return 0;
if (array.Length == 1 && array[0] != 1) return -1;
return BinarySearch01 (array, 0, array.Length - 1);
}
/// <summary>
/// Recursively find the index of the first 1 in given list of 0's and 1's in which all the 0's come before 1's.
/// </summary>
private static int BinarySearch01 (int[] array, int start, int end)
{
if (end < start)
{
return -1;
}
int middle = (start + end) / 2;
if (array[middle] == 1 && array[middle - 1] == 0)
{
return middle;
}
if (array[middle] == 0)
{
return BinarySearch01 (array, middle + 1, end);
}
else
{
return BinarySearch01 (array, start, middle - 1);
}
}
}
}