其他分享
首页 > 其他分享> > 手写快排,解决栈溢出写法,Golang

手写快排,解决栈溢出写法,Golang

作者:互联网

package main

import "fmt"

var swapcnt int

func main() {
	arr := []int{2, 3, 4, 5, 1}
	//idx := Swap(arr, 0, len(arr))
	//fmt.Println(idx, arr)
	myquickSort(arr, 0, len(arr)-1)
	fmt.Println(arr)
	fmt.Println(swapcnt)
}

func Swap(arr []int, l, r int) int {
	idx := l
	pivot := arr[r]
	for i := l; i <= r; i++ {
		if arr[i] <= pivot {
			if idx != i {
				arr[idx], arr[i] = arr[i], arr[idx]
				swapcnt += 1
			}
			idx += 1
		}
	}
	return idx - 1
}

func myquickSort(nums []int, l, r int) {
	if l < r {
		m := Swap(nums, l, r)
		myquickSort(nums, l, m-1)
		myquickSort(nums, m+1, r)
	}
}

func quickSort(nums []int, l, r int) { //[l,r]
	if l < r {
		m := partition(nums, l, r)
		quickSort(nums, l, m-1)
		quickSort(nums, m+1, r)
	}
}

func partition(nums []int, l int, r int) int {
	key := nums[r]
	i, j := l, l
	for j < r {
		if nums[j] < key {
			nums[i], nums[j] = nums[j], nums[i]
			i++
		}
		j++
	}
	nums[i], nums[r] = nums[r], nums[i]
	return i
}

// 解决栈溢问题
func qsort(arr []int, left, right int) {
	tmp := arr[(left+right)/2]
	i, j := left, right
	for i <= j {
		for arr[i] > tmp {
			i--
		}
		for arr[i] < tmp {
			i++
		}
		if i <= j {
			arr[i], arr[j] = arr[j], arr[i]
			i++
			j--
		}
	}
	if i < right {
		qsort(arr, i, right)
	}
	if j > left {
		qsort(arr, left, j)
	}

}

标签:arr,idx,int,swapcnt,fmt,Golang,快排,Println,手写
来源: https://www.cnblogs.com/notomatoes/p/16642753.html