[ Cmii ] [ Octopus ] - add Image Function - 1
This commit is contained in:
@@ -1,51 +1 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
// quic sort s a slice of ints using quicksort algorithm.
|
||||
// The function returns nothing. It modifies the slice in place.
|
||||
func QuickSort(a []int) { // <-- pass by value, so we can't modify it
|
||||
quick_sort(0, len(a)-1, a)
|
||||
}
|
||||
|
||||
/*
|
||||
* The following function implements the quicksort algorithm. It requires three parameters:
|
||||
* left: an index indicating the left bound of the subarray to be sorted.
|
||||
* right: an index indicating the right bound of the subarray to be sorted.
|
||||
* a: the slice of integers to sort. The function modifies the slice in place.
|
||||
*/
|
||||
func quick_sort(left int, right int, a []int) {
|
||||
if left < right { // only continue if there is more than one element in the subarray
|
||||
pivot := partition(left, right, a)
|
||||
quick_sort(left, pivot-1, a)
|
||||
quick_sort(pivot+1, right, a) // <-- call this function again on the right half of the subarray
|
||||
} else { // if there is only one element in the subarray, we can return immediately
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func partition(left int, right int, a []int) int {
|
||||
// find a pivot element. This is just one of the examples in the book
|
||||
pivot := a[right]
|
||||
|
||||
// index i will keep track of where to put the pivot element
|
||||
i := left - 1
|
||||
|
||||
// swap the pivot element with a[right]
|
||||
a[right], a[left] = a[left], a[right]
|
||||
|
||||
for j := left; j < right; j++ {
|
||||
if a[j] <= pivot {
|
||||
i += 1 // increment i
|
||||
a[i], a[j] = a[j], a[i]
|
||||
}
|
||||
}
|
||||
|
||||
return i + 1 // put the pivot element at its final position
|
||||
}
|
||||
|
||||
func main() {
|
||||
arr := []int{2, 45, 36, -78, 90, 1000, -1, 0, -76}
|
||||
QuickSort(arr)
|
||||
fmt.Println("Sorted array:", arr)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user