Skip to content

Commit f2c51d4

Browse files
committed
Added 72. Sort Colors
1 parent 6c35f2c commit f2c51d4

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package sort_colors
2+
3+
func SortColors(nums []int) []int {
4+
low := 0
5+
mid := 0
6+
high := len(nums) - 1
7+
8+
for mid <= high {
9+
if nums[mid] == 0 {
10+
temp := nums[mid]
11+
nums[mid] = nums[low]
12+
nums[low] = temp
13+
14+
mid++
15+
low++
16+
} else if nums[mid] == 1 {
17+
mid++
18+
} else if nums[mid] == 2 {
19+
temp := nums[mid]
20+
nums[mid] = nums[high]
21+
nums[high] = temp
22+
23+
high--
24+
}
25+
}
26+
27+
return nums
28+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package sort_colors
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
func TestSortColors(t *testing.T) {
9+
tests := []struct {
10+
name string
11+
nums []int
12+
expectedResult []int
13+
} {
14+
{
15+
name: "Test Case 1",
16+
nums: []int{2,0,2,1,1,0},
17+
expectedResult: []int{0,0,1,1,2,2},
18+
},
19+
{
20+
name: "Test Case 2",
21+
nums: []int{2, 0 ,1},
22+
expectedResult: []int{0, 1, 2},
23+
},
24+
}
25+
26+
for _, test := range tests {
27+
t.Run(test.name, func(t * testing.T) {
28+
got := SortColors(test.nums)
29+
if !reflect.DeepEqual(got, test.expectedResult){
30+
t.Errorf("SortColors(%v) = %v; want = %v", test.nums, got, test.expectedResult)
31+
}
32+
})
33+
}
34+
}

0 commit comments

Comments
 (0)