Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import "fmt"
- type Pair struct {
- first int
- second int
- }
- type stack []Pair
- func (s *stack)Push(p Pair){
- *s = append(*s, p)
- }
- func (s *stack)Pop() Pair{
- if s.IsEmpty(){
- panic(s)
- }
- l := len(*s)
- res := (*s)[l-1]
- *s = (*s)[:l-1]
- return res
- }
- func (s *stack)IsEmpty() bool{
- return len(*s) == 0
- }
- func partition(l int, r int, less func(i,j int) bool, swap func(i, j int)) int{
- i := l
- middle := (r+l)/2
- j := r-1
- for i <= j{
- for less(i,middle){
- i++
- }
- for less(middle,j){
- j--
- }
- if i >= j{
- break
- }
- if i == middle{
- middle = j
- }else if j == middle{
- middle = i
- }
- swap(i,j)
- i++
- j--
- }
- return j
- }
- func qsort(n int, less func(i,j int) bool, swap func(i, j int)){
- var s stack
- s.Push(Pair{0,n})
- for !s.IsEmpty() {
- pair := s.Pop()
- size := pair.second - pair.first
- if size < 2 {
- continue
- }
- median := (pair.second +pair.first)/2
- if less(median, pair.first) {
- swap(pair.first, median)
- }
- if less(pair.second-1, pair.first) {
- swap(pair.second-1, pair.first)
- }
- if less(median, pair.second-1) {
- swap(median, pair.second-1)
- }
- q := partition(pair.first,pair.second,less,swap)
- if pair.first < q + 1 && q + 1 < pair.second{
- s.Push(Pair{pair.first,q+1})
- s.Push(Pair{q+1,pair.second})
- }
- }
- }
- func main() {
- var n, tmp int
- var arr []int
- fmt.Scan(&n)
- for i := 0; i < n; i++{
- fmt.Scan(&tmp)
- arr = append(arr, tmp)
- }
- qsort(n,
- func(i, j int) bool{
- return arr[i] < arr[j]
- },
- func(i, j int){
- arr[i], arr[j] = arr[j], arr[i]
- })
- for i:= 0; i < n; i++{
- fmt.Printf("%d ",arr[i])
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement