go快速排序 数组&链表

线性表:

func sortArray(nums []int) []int {
	
	return quickSort(nums,0,len(nums)-1)

}
func quickSort(nums []int,start,end int)[]int{
	if start < end{
		partitionkey := partition(nums,start,end)
		quickSort(nums,start,partitionkey-1)
		quickSort(nums,partitionkey+1,end)
	}
	return nums
}
func partition(nums []int,start,end int)int{
	pivot := nums[start]
	for start < end{
		for start < end && nums[end] >= pivot{
			end --
		}
		nums[start],nums[end] = nums[end],nums[start]

		for start < end && nums[start] <= pivot{
			start++
		}
		nums[start],nums[end] = nums[end],nums[start]

	}
	return start

}

链表:

func swap(a,b *ListNode){
	a.Val , b.Val = b.Val,a.Val
}
func quicksort(head,end *ListNode){

	if head == end || head.Next == nil{
		return
	}
	slow , fast := head, head.Next
	pivot := head.Val
	for fast != nil{
		if fast.Val <= pivot{
			slow = slow.Next
			swap(slow,fast)
		}
		fast = fast.Next
	}
	swap(head,slow)
	quicksort(head,slow)
	quicksort(slow.Next,end)
}

 

你可能感兴趣的:(goLang)