funcshellSort(array []int, length int) { for gap := length / 2; gap > 0; gap = gap / 2 { for i := gap; i < length; i++ { var j = i for { if j-gap < 0 || array[j] >= array[j-gap] { break } swap(array, j, j-gap) j = j - gap } } } }
funcmergeSort(arr []int) []int { length := len(arr) if length < 2 { return arr } middle := length / 2 left := arr[:middle] right := arr[middle:] return merge(mergeSort(left), mergeSort(right)) }
funcmerge(left []int, right []int) []int { var result []int forlen(left) != 0 && len(right) != 0 { if left[0] < right[0] { result = append(result, left[0]) left = left[1:] } else { result = append(result, right[0]) right = right[1:] } } forlen(left)!=0{ result = append(result, left[0]) left = left[1:] } forlen(right)!=0{ result = append(result, right[0]) right = right[1:] } return result }
funcpartition(nums []int, left int, right int)int { value := nums[left] // 基准值 for left < right { for nums[right] >= value && left < right { // 依次查找大于等于基准值的位置 right-- } nums[left] = nums[right] for nums[left] < value && left < right { // 依次查找小于基准值的位置 left++ } nums[right] = nums[left] } nums[left] = value // 最终 left == right 就是基准值的位置 return left }
funcQuickSort(list []int, left int, right int) { if left < right { middle := partition(list, left, right) QuickSort(list, left, middle-1) QuickSort(list, middle+1, right) } }
funcbuildMaxHeap(arr []int, arrLen int) { for i := arrLen / 2; i >= 0; i-- { heapify(arr, i, arrLen) } }
funcheapify(arr []int, i, arrLen int) { left := 2*i + 1 right := 2*i + 2 largest := i if left < arrLen && arr[left] > arr[largest] { largest = left } if right < arrLen && arr[right] > arr[largest] { largest = right } if largest != i { swap(arr, i, largest) heapify(arr, largest, arrLen) } }
funcBucket(arr []int) { //将数组装入桶中 bucket := make(map[int][]int) for _, val := range arr { bucket[val/10] = append(bucket[val/10], val) } //各个桶内进行从小到大排序 for _, val := range bucket { sort.Ints(val) } //由于map无序,因此需要获取map的key的有序集合 var keys []int for key := range bucket { keys = append(keys, key) } sort.Ints(keys)
//桶内元素转入数组中 index := 0 for _, key := range keys { for _, val := range bucket[key] { arr[index] = val index++ } } }