Skip to content

Commit 10892b5

Browse files
Adding quicksort
1 parent b69de8c commit 10892b5

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Go/sorting/quicksort.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package sorting
2+
3+
func partition(arr []int, start, end int) int {
4+
pivotIndex := start
5+
pivot := arr[start]
6+
7+
smaller := start + 1 // All elements less than pivot
8+
larger := start + 1 // All elements greater than pivot
9+
10+
for larger = start + 1; larger <= end; larger++ {
11+
if arr[larger] < pivot {
12+
arr[smaller], arr[larger] = arr[larger], arr[smaller]
13+
smaller++
14+
}
15+
}
16+
17+
// put pivot to it's right place
18+
arr[pivotIndex], arr[smaller-1] = arr[smaller-1], arr[pivotIndex]
19+
return smaller - 1 // Return the current pivot index!
20+
}
21+
func quickSort(arr []int, start, end int) {
22+
if start < end {
23+
pivotIndex := partition(arr, start, end)
24+
quickSort(arr, start, pivotIndex)
25+
quickSort(arr, pivotIndex+1, end)
26+
}
27+
}

0 commit comments

Comments
 (0)