C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
And: In Example 2 we force the search to end at the maximum number of elements by changing the data after the last valid element.
IfThen: We can use a single check for each element to ensure validity. Example2 has only one if-statement.
C# program that uses sentinel
using System;
class Program
{
static void Main()
{
Console.WriteLine(Example1(5));
Console.WriteLine(Example2(5));
}
static int Example1(int n)
{
// Count number of elements greater than zero in first N elements.
int[] array = { 1, 1, 2, 2, 3, 3, 4, 4, 5, 5 };
// Loop.
int position = 0;
int count = 0;
while (true)
{
if (position >= n)
{
break;
}
if (array[position] <= 0)
{
break;
}
count++;
position++;
}
return count;
}
static int Example2(int n)
{
// Count number of elements greater than zero in first N elements.
int[] array = { 1, 1, 2, 2, 3, 3, 4, 4, 5, 5 };
// Assign a sentinel.
array[n] = 0;
// Loop.
int position = 0;
int count = 0;
while (true)
{
if (array[position] <= 0)
{
break;
}
count++;
position++;
}
return count;
}
}
Output
5
5
Tip: You can mutate the data source to reduce the number of logical checks in an inner loop, improving performance by reducing branches.