Skip to content

Commit a22d6bf

Browse files
author
Nemanja
committed
Add QuickSort implementation
1 parent 79092a2 commit a22d6bf

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

sort-algorithms/QuickSort.go

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"go-sort-algorithms/utils"
6+
)
7+
8+
func QuickSort(items []int) {
9+
10+
stack := utils.Stack{}
11+
stack.Push(0)
12+
stack.Push(len(items) - 1)
13+
14+
for !stack.IsEmpty() {
15+
16+
endIndex := stack.Pop()
17+
startIndex := stack.Pop()
18+
19+
partitionElementIndex := partition(items, startIndex, endIndex)
20+
21+
if partitionElementIndex - 1 > startIndex {
22+
stack.Push(startIndex)
23+
stack.Push(partitionElementIndex - 1)
24+
}
25+
26+
if partitionElementIndex + 1 < endIndex {
27+
stack.Push(partitionElementIndex + 1)
28+
stack.Push(endIndex)
29+
}
30+
}
31+
32+
}
33+
34+
func partition(items []int, startIndex, endIndex int) int {
35+
36+
i := startIndex + 1
37+
j := endIndex
38+
39+
for true {
40+
41+
for items[i] < items[startIndex] {
42+
i++
43+
if i == endIndex {
44+
break
45+
}
46+
}
47+
48+
for items[startIndex] < items[j] {
49+
j--
50+
if j == startIndex {
51+
break
52+
}
53+
}
54+
55+
if i >= j {
56+
break
57+
}
58+
utils.Swap(items, i, j)
59+
}
60+
utils.Swap(items, startIndex, j)
61+
return j
62+
}
63+
64+
65+
func main() {
66+
67+
numbers := utils.GetNumbers()
68+
fmt.Println("Unsorted numbers", numbers)
69+
70+
QuickSort(numbers)
71+
fmt.Println("Sorted numbers", numbers)
72+
}

0 commit comments

Comments
 (0)