1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| func sortArray(nums []int) []int { len := len(nums) heapSort(nums, len)
return nums }
func heapSort(nums []int, len int) { buildHeap(nums, len) for len > 1 { nums[0], nums[len-1] = nums[len-1], nums[0] len-- adjestHeap(nums, 0, len) } }
func buildHeap(nums []int, len int) { for i := (len/2)-1; i >= 0; i-- { adjestHeap(nums, i, len) } }
func adjestHeap(nums []int, i, len int) { for 2*(i+1) <= len { leftChild := 2*(i+1)-1 rightChild := leftChild+1 var larger int if rightChild < len && nums[rightChild] > nums[leftChild] { larger = rightChild } else { larger = leftChild } if nums[i] < nums[larger] { nums[i], nums[larger] = nums[larger], nums[i] } i = larger } }
|