[ Cmii ] [ Octopus ] - add some features

This commit is contained in:
zeaslity
2024-03-22 16:09:57 +08:00
parent 8e6f09d522
commit 46b9ba59e9
8 changed files with 105 additions and 31 deletions

51
agent-go/tmp/test.go Normal file
View File

@@ -0,0 +1,51 @@
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)
}