Search⌘ K
AI Features

Solution: The Dutch National Flag Problem

Learn how to solve the Dutch National Flag problem by exploring both naive and optimized solutions. Understand how selection sort operates with O(n²) complexity and discover a more efficient three-way partitioning algorithm that achieves O(n) time complexity using a single array pass.

Solution 1: Brute force

C#
using System;
class Program
{
/// <summary>
/// This method uses the selection sort approach to solve the Dutch National Flag Problem.
/// </summary>
/// <param name="arr">An array of integers.</param>
/// <returns>An array with the Dutch National Flag Problem solved.</returns>
public static int[] DutchNationalFlag(int[] arr)
{
int size = arr.Length;
int index;
for (int i = 0; i < size; i++)
{
index = FindMin(arr, i, size);
Swap(arr, i, index);
}
return arr;
}
/// <summary>
/// Finds the minimum value index in an array within a specific range.
/// </summary>
/// <param name="arr">An array of integers.</param>
/// <param name="start">Starting index.</param>
/// <param name="end">Ending index.</param>
/// <returns>The index of the minimum value within the specified range.</returns>
public static int FindMin(int[] arr, int start, int end)
{
int min = arr[start];
int index = start;
for (int x = start; x < end; x++)
{
if (arr[x] < min)
{
min = arr[x];
index = x;
}
}
return index;
}
// Swaps numbers in an array
public static void Swap(int[] arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// Driver to test above code
public static void Main()
{
int[] array = { 2, 0, 0, 1, 2, 1 };
int[] result = DutchNationalFlag(array);
Console.WriteLine("[" + string.Join(", ", result) + "]");
}
}

Explanation

We use a simple selection sort to rearrange the array in ascending order. This method is naive and does not cater to the fact that we have just three different digits for this problem.

Time complexity

The time complexity is O(n2 ...