1. 经典排序

1.1. 堆排序

显示代码
 func heapSort(nums []int) []int {

     lens := len(nums)
     buildHeap(nums,lens)
     for i:=lens-1;i>=0;i-- {
         swap(nums,0,i)
         lens -= 1
         heap(nums,0,lens)
     }

     return nums
 }

 func buildHeap(nums []int,lens int) {
     for i := lens/2;i>=0;i-- {
         heap(nums,i,lens)
     }
     fmt.Println(nums)
 }

 func heap(nums []int,i,lens int) {
     left := 2*i + 1
     right := 2*i + 2

     largest := i
     if left < lens && nums[left] > nums[largest] {
         largest = left
     }
     if right < lens && nums[right] > nums[largest] {
         largest = right
     }

     if largest != i {
         swap(nums,largest,i)
         heap(nums,largest,lens)
     }

 }


 func swap(arr []int,m,n int) []int {
     arr[m],arr[n] = arr[n],arr[m]
     return arr
 }

results matching ""

    No results matching ""