Dutch National Flag problem efficiently sorts an array containing only 0s, 1s, and 2s. This approach sorts the array in a single pass with a time complexity of O(n) and a space complexity of O(1). It uses three-pointers to partition the array into three sections: one for 0s, one for 1s, and one for 2s.

public void SortColors(int[] nums)
{
    int low = 0, mid = 0, high = nums.Length - 1;

    while (mid <= high)
    {
        if (nums[mid] == 0)
        {
            Swap(nums, low++, mid++);
        }
        else if (nums[mid] == 1)
        {
            mid++;
        }
        else
        {
            Swap(nums, mid, high--);
        }
    }
}

private void Swap(int[] nums, int i, int j)
{
    int temp = nums[i];
    nums[i] = nums[j];
    nums[j] = temp;
}

Initialization

Traversal and Sorting

Termination

This algorithm is efficient with a time complexity of O(n) and a space complexity of O(1), making it optimal for this problem.

Here's a step-by-step explanation:

Initialization

Traversal and Sorting:

Termination:

Let's take an example array: [0, 0, 1, 1, 2, 2]

Step-by-Step Process

  1. Initial State

    • Array: [2, 0, 2, 1, 1, 0]
    • low = 0, mid = 0, high = 5
  2. First Iteration (mid = 0)

    • nums[mid] is 2.
    • Swap nums[mid] with nums[high].
    • Decrement high.
    • Array: [0, 0, 2, 1, 1, 2]
    • low = 0, mid = 0, high = 4
  3. Second Iteration (mid = 0)

    • nums[mid] is 0.
    • Swap nums[mid] with nums[low].
    • Increment both low and mid.
    • Array: [0, 0, 2, 1, 1, 2]
    • low = 1, mid = 1, high = 4
  4. Third Iteration (mid = 1)

    • nums[mid] is 0.
    • Swap nums[mid] with nums[low].
    • Increment both low and mid.
    • Array: [0, 0, 2, 1, 1, 2]
    • low = 2, mid = 2, high = 4
  5. Fourth Iteration (mid = 2)

    • nums[mid] is 2.
    • Swap nums[mid] with nums[high].
    • Decrement high.
    • Array: [0, 0, 1, 1, 2, 2]
    • low = 2, mid = 2, high = 3
  6. Fifth Iteration (mid = 2)

    • nums[mid] is 1.
    • Increment mid.
    • Array: [0, 0, 1, 1, 2, 2]
    • low = 2, mid = 3, high = 3
  7. Sixth Iteration (mid = 3)

    • nums[mid] is 1.
    • Increment mid.
    • Array: [0, 0, 1, 1, 2, 2]
    • low = 2, mid = 4, high = 3

Termination

Final Sorted Array