FlareStart
HomeNewsHow ToSources
FlareStart

Where developers start their day. All the tech news & tutorials that matter, in one place.

Quick Links

  • Home
  • News
  • Tutorials
  • Sources
  • Privacy Policy

Connect

© 2026 FlareStart. All rights reserved.

Back to articles
Sort an Array of 0s, 1s and 2s
NewsMachine Learning

Sort an Array of 0s, 1s and 2s

via Dev.toARUL SELVI ML2h ago

Sort an Array of 0s, 1s and 2s Problem Statement Given an array consisting of only 0s, 1s and 2s, sort the array in ascending order. Examples Input arr = [0, 2, 1, 2, 0] Output [0, 0, 1, 2, 2] Input arr = [2, 0, 1] Output [0, 1, 2] Approach 1 Using Sorting The simplest way is to sort the array using built in functions. Code ```python id="sort1" def sortArray(arr): arr.sort() return arr --- ## Approach 2 Counting Method Count the number of 0s, 1s and 2s, then overwrite the array. --- ### Steps 1 Count number of 0s, 1s and 2s 2 Fill array with 0s 3 Then fill with 1s 4 Then fill with 2s --- ### Code ```python id="sort2" def sortArray(arr): count0 = arr.count(0) count1 = arr.count(1) count2 = arr.count(2) i = 0 for _ in range(count0): arr[i] = 0 i += 1 for _ in range(count1): arr[i] = 1 i += 1 for _ in range(count2): arr[i] = 2 i += 1 return arr Approach 3 Dutch National Flag Algorithm This is the most efficient method. Steps 1 Maintain three pointers low, mid and high 2 low is for 0 place

Continue reading on Dev.to

Opens in a new tab

Read Full Article
0 views

Related Articles

News

Book Overview: The Clean Coder

Medium Programming • 24m ago

MIT’s Test 2012: Subtract 27² from 25³
News

MIT’s Test 2012: Subtract 27² from 25³

Medium Programming • 25m ago

T-Mobile will give you an iPhone 17 for free - here's how the deal works
News

T-Mobile will give you an iPhone 17 for free - here's how the deal works

ZDNet • 33m ago

Our Favorite Turntable Is $51 Off Before Record Store Day
News

Our Favorite Turntable Is $51 Off Before Record Store Day

Wired • 38m ago

News

Addressing global removal race in Wayland

Lobsters • 55m ago

Discover More Articles