Skip to content

Commit 21febd8

Browse files
committed
Add quick sort algorithm
1 parent 644718c commit 21febd8

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package main
2+
3+
import "fmt"
4+
5+
func quickSort(arr []int, start, end int) {
6+
if start < end {
7+
pivot := partition(arr, start, end)
8+
quickSort(arr, start, pivot - 1)
9+
quickSort(arr, pivot + 1, end)
10+
}
11+
}
12+
13+
func partition(arr []int, start, end int) int {
14+
pivot := arr[start]
15+
low := start
16+
high := end
17+
18+
for start < end {
19+
for arr[start] <= pivot && start < high {
20+
start++
21+
}
22+
for arr[end] > pivot && end > low {
23+
end--
24+
}
25+
26+
if start < end {
27+
arr[start], arr[end] = arr[end], arr[start]
28+
}
29+
}
30+
31+
arr[low], arr[end] = arr[end], pivot
32+
return end
33+
}
34+
35+
func main() {
36+
sortArr := []int{40, 50, 20, 0, -10, 30, 10}
37+
quickSort(sortArr, 0, len(sortArr) - 1)
38+
fmt.Println(sortArr)
39+
}

0 commit comments

Comments
 (0)