golang 版快速排序

前端之家收集整理的这篇文章主要介绍了golang 版快速排序前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

快速排序作为经典算法,基本面试中都会遇到,今天记录一下。

1.非递归版,这里也是使用一个栈的模型(自己实现)来实现。需要注意的是interface转int需要断言。

package main

import (
	"container/list"
	"fmt"
)

// Stack is stack
type Stack struct {
	stack *list.List
}

func newStack() *Stack {
	list := list.New()
	return &Stack{list}
}

func (Stack *Stack) push(value interface{}) {
	Stack.stack.PushBack(value)
}

func (Stack *Stack) pop() interface{} {
	e := Stack.stack.Back()
	if e != nil {
		Stack.stack.Remove(e)
		return e.Value
	}
	return nil
}

func (Stack *Stack) isEmpty() bool {
	return Stack.stack.Len() == 0
}

func main() {
	var nums = []int{4,1,89,18,10}
	quickSort(nums,len(nums)-1)
	fmt.Println(nums)
}

func quickSort(nums []int,low,high int) {
	stack := newStack()
	if low < high {
		stack.push(high)
		stack.push(low)
		for low < high {
			left,ok := stack.pop().(int)
			if !ok {
				break
			}
			right,ok := stack.pop().(int)
			if !ok {
				break
			}
			pivot := partition(nums,left,right)

			if left < pivot-1 {
				stack.push(pivot - 1)
				stack.push(left)
			}

			if right > pivot+1 {
				stack.push(right)
				stack.push(pivot + 1)
			}
		}
	}
}

func partition(nums []int,high int) int {
	pivotKey := nums[high]
	for low < high {
		for low < high && nums[low] < pivotKey {
			low++
		}
		nums[low],nums[high] = nums[high],nums[low]

		for low < high && nums[high] > pivotKey {
			high--
		}
		nums[low],nums[low]
	}

	return high
}
2.递归版
package main

import "fmt"

func main() {
	var nums = []int{4,10}
	quickSort(nums)
	fmt.Println(nums)
}

func quickSort(nums []int) {
	qSort(nums,len(nums)-1)
}

func qSort(nums []int,high int) {
	if low < high {
		pivot := partition(nums,high)
		qSort(nums,pivot-1)
		qSort(nums,pivot+1,high)
	}
}

func partition(nums []int,high int) int {
	pivotKey := nums[low]
	for low < high {
		for low < high && nums[high] > pivotKey {
			high--
		}
		nums[low],nums[low]

		for low < high && nums[low] < pivotKey {
			low++
		}
		nums[low],nums[low]
	}

	return low
}

猜你在找的Go相关文章