funcswap(x, y int)(int,int){return y, x
}funcQuickSort(nums []int, left, right int){if(left >= right){return}
mid :=((right - left)>>1)+ left
nums[left], nums[mid]=swap(nums[left], nums[mid])
l, r, pivot := left, right +1, nums[left]for l < r {for l < right {
l++if nums[l]>= pivot {break}}for r > left {
r--if nums[r]<= pivot {break}}if l < r {
nums[l], nums[r]=swap(nums[l], nums[r])}else{break}}
nums[left], nums[r]=swap(nums[left], nums[r])QuickSort(nums, left, r -1)QuickSort(nums, r +1, right)}funcsortArray(nums []int)[]int{QuickSort(nums,0,len(nums)-1)return nums
}
代码实现(八刷自解 DAY 10 Golang)
type Heap struct{
heap []int}func(this *Heap)Construct(nums []int){
this.heap = nums
for i :=len(this.heap)/2; i >=0; i--{
this.Heapify(i)}}func(this *Heap)Heapify(pos int){
val, nextpos := this.heap[pos], pos *2+1
size :=len(this.heap)for; nextpos < size; nextpos = nextpos *2+1{if nextpos < size -1&& this.heap[nextpos]> this.heap[nextpos +1]{
nextpos = nextpos +1}if val > this.heap[nextpos]{
this.heap[pos]= this.heap[nextpos]
pos = nextpos
}else{break}}
this.heap[pos]= val
}func(this *Heap)Push(val int){
this.heap =append(this.heap, val)
pos :=len(this.heap)-1for pos >0{if this.heap[(pos -1)/2]> this.heap[pos]{
this.heap[pos]= this.heap[(pos -1)/2]
pos =(pos -1)/2}else{break}}
this.heap[pos]= val
}func(this *Heap)Pop()int{
ret := this.heap[0]
this.heap[0]= this.heap[len(this.heap)-1]
this.Heapify(0)
this.heap = this.heap[:len(this.heap)-1]return ret
}func(this *Heap)Empty()bool{returnlen(this.heap)==0}funcsortArray(nums []int)[]int{
heap_ := Heap{}
heap_.Construct(nums)
ret :=make([]int,0)for heap_.Empty()==false{
ret =append(ret, heap_.Pop())}return ret
}
代码实现(九刷自解 DAY 12 golang)
funcmergeSort(nums, tmp []int, left, right int){if left >= right {return}
mid :=((right - left)>>1)+ left
mergeSort(nums, tmp, left, mid)mergeSort(nums, tmp, mid +1, right)
l, r, pos := left, mid +1, left
for l <= mid && r <= right {if nums[l]<= nums[r]{
tmp[pos]= nums[l]
l++}else{
tmp[pos]= nums[r]
r++}
pos++}for l <= mid {
tmp[pos]= nums[l]
pos, l = pos +1, l +1}for r <= right {
tmp[pos]= nums[r]
pos, r = pos +1, r +1}for i := left; i <= right; i++{
nums[i]= tmp[i]}}funcsortArray(nums []int)[]int{
tmp :=make([]int,len(nums))mergeSort(nums, tmp,0,len(tmp)-1)return nums
}