
Sorting an Array of 0s, 1s and 2s - CA08
Introduction Sorting is a fundamental concept in programming. In this problem, we are given an array that contains only three distinct values: 0s, 1s, and 2s . The goal is to sort the array in ascending order without using any built-in sorting functions. This problem is important because it introduces an efficient technique known as the Dutch National Flag Algorithm . Problem Statement Given an array arr[] containing only 0s, 1s, and 2s, sort the array in ascending order. Constraints: Do not use built-in sorting functions Aim for an efficient solution Example 1 Input: arr = [ 0 , 1 , 2 , 0 , 1 , 2 ] Output: [ 0 , 0 , 1 , 1 , 2 , 2 ] Example 2 Input: arr = [ 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 ] Approach 1: Counting Method Python Implementation (Counting) def sort_array ( arr ): count0 = arr . count ( 0 ) count1 = arr . count ( 1 ) count2 = arr . count ( 2 ) i = 0 # Fill 0s for _ in range ( count0 ): arr [ i ] = 0 i +=
Continue reading on Dev.to Tutorial
Opens in a new tab



