tangs пре 5 година
родитељ
комит
d657aa56a8
1 измењених фајлова са 67 додато и 0 уклоњено
  1. 67 0
      tags/sort/sortColors/main.go

+ 67 - 0
tags/sort/sortColors/main.go

@@ -0,0 +1,67 @@
+package main
+
+import "fmt"
+
+func main() {
+	var nums []int
+
+	nums = []int{}
+	sortColors(nums)
+	fmt.Println(nums)
+
+	nums = []int{1}
+	sortColors(nums)
+	fmt.Println(nums)
+
+	nums = []int{0, 1}
+	sortColors(nums)
+	fmt.Println(nums)
+
+	nums = []int{0, 1, 2}
+	sortColors(nums)
+	fmt.Println(nums)
+
+	nums = []int{2, 0, 1, 2}
+	sortColors(nums)
+	fmt.Println(nums)
+
+	nums = []int{0, 1, 2, 0, 2}
+	sortColors(nums)
+	fmt.Println(nums)
+
+	nums = []int{2, 0, 2, 1, 1, 0}
+	sortColors(nums)
+	fmt.Println(nums)
+}
+
+func sortColors(nums []int) {
+	var front, back = increase(nums, 0, 0), decrease(nums, len(nums)-1, 2)
+	for i := front; i <= back; i++ {
+		if nums[i] == 0 {
+			nums[front], nums[i] = nums[i], nums[front]
+			front = increase(nums, front, 0)
+			i = front - 1
+			continue
+		}
+		if nums[i] == 2 {
+			nums[back], nums[i] = nums[i], nums[back]
+			back = decrease(nums, back, 2)
+			i--
+			continue
+		}
+	}
+}
+
+func increase(nums []int, index, val int) int {
+	for index < len(nums) && nums[index] == val {
+		index++
+	}
+	return index
+}
+
+func decrease(nums []int, index, val int) int {
+	for index >= 0 && nums[index] == val {
+		index--
+	}
+	return index
+}