Back to articles
🔵 Sort 0s, 1s and 2s (Dutch National Flag Algorithm)

🔵 Sort 0s, 1s and 2s (Dutch National Flag Algorithm)

via Dev.toNavin S

Sorting an array containing only 0s, 1s, and 2s is a classic problem in Data Structures. It is commonly solved using the Dutch National Flag Algorithm , which is highly efficient. 📌 Problem Statement Given an array arr[] containing only 0 , 1 , and 2 , sort the array in ascending order without using built-in sort . 🔍 Examples Example 1: Input: [0, 1, 2, 0, 1, 2] Output: [0, 0, 1, 1, 2, 2] Example 2: Input: [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1] Output: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2] 🧠 Concept We divide the array into three regions : Left → all 0s Middle → all 1s Right → all 2s We use three pointers : low → position for next 0 mid → current element high → position for next 2 🔄 Approach: One-Pass (Optimal Solution) Step-by-Step: Initialize: low = 0 mid = 0 high = n - 1 Traverse while mid <= high : If arr[mid] == 0 : Swap arr[low] and arr[mid] low++ , mid++ If arr[mid] == 1 : Move mid++ If arr[mid] == 2 : Swap arr[mid] and arr[high] high-- (do NOT increment mid here) 💻 Python Code ```

Continue reading on Dev.to

Opens in a new tab

Read Full Article
5 views

Related Articles