Skip to content

Commit 1381ed0

Browse files
feat: add dutchNationalFlagSort implementation (TheAlgorithms#1305)
* feat: add dutchNationalFlagSort implementation * fix: add test, fit code style * fix: add link to directory.md
1 parent 327e18f commit 1381ed0

File tree

3 files changed

+43
-0
lines changed

3 files changed

+43
-0
lines changed

DIRECTORY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,7 @@
303303
* [CombSort](Sorts/CombSort.js)
304304
* [CountingSort](Sorts/CountingSort.js)
305305
* [CycleSort](Sorts/CycleSort.js)
306+
* [DutchNationalFlagSort](Sorts/DutchNationalFlagSort.js)
306307
* [FindSecondLargestElement](Sorts/FindSecondLargestElement.js)
307308
* [FisherYatesShuffle](Sorts/FisherYatesShuffle.js)
308309
* [FlashSort](Sorts/FlashSort.js)

Sorts/DutchNationalFlagSort.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* @function dutchNationalFlagSort
3+
* @description Dutch National Flag Sort is an algorithm to sort an array containing 0s, 1s, and 2s in linear time.
4+
Time complexity of Dutch National Flag Sort Algorithm is O(n).
5+
Auxiliary Space required for Dutch National Flag Sort Algorithm is O(1).
6+
* @param {Integer[]} nums - Array of integers containing 0s, 1s, and 2s.
7+
* @return {Integer[]} - Array of integers sorted in non-decreasing order.
8+
* @see [Dutch National Flag Sort](https://en.wikipedia.org/wiki/Dutch_national_flag_problem)
9+
*/
10+
export function dutchNationalFlagSort (nums) {
11+
let low = 0
12+
let mid = 0
13+
let high = nums.length - 1
14+
15+
while (mid <= high) {
16+
switch (nums[mid]) {
17+
case 0:
18+
[nums[low], nums[mid]] = [nums[mid], nums[low]]
19+
low++
20+
mid++
21+
break
22+
case 1:
23+
mid++
24+
break
25+
case 2:
26+
[nums[mid], nums[high]] = [nums[high], nums[mid]]
27+
high--
28+
break
29+
}
30+
}
31+
32+
return nums
33+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import { dutchNationalFlagSort } from '../DutchNationalFlagSort'
2+
3+
describe('DutchNationalFlagSort', () => {
4+
it('should sort arrays correctly', () => {
5+
expect(dutchNationalFlagSort([2, 0, 2, 1, 1, 0])).toEqual([0, 0, 1, 1, 2, 2])
6+
expect(dutchNationalFlagSort([2, 1, 0])).toEqual([0, 1, 2])
7+
expect(dutchNationalFlagSort([1, 0, 0, 0, 1])).toEqual([0, 0, 0, 1, 1])
8+
})
9+
})

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy