github.com/goproxy0/go@v0.0.0-20171111080102-49cc0c489d2c/src/sort/slice.go (about) 1 // Copyright 2017 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // +build !compiler_bootstrap go1.8 6 7 package sort 8 9 import "reflect" 10 11 // Slice sorts the provided slice given the provided less function. 12 // 13 // The sort is not guaranteed to be stable. For a stable sort, use 14 // SliceStable. 15 // 16 // The function panics if the provided interface is not a slice. 17 func Slice(slice interface{}, less func(i, j int) bool) { 18 rv := reflect.ValueOf(slice) 19 swap := reflect.Swapper(slice) 20 length := rv.Len() 21 quickSort_func(lessSwap{less, swap}, 0, length, maxDepth(length)) 22 } 23 24 // SliceStable sorts the provided slice given the provided less 25 // function while keeping the original order of equal elements. 26 // 27 // The function panics if the provided interface is not a slice. 28 func SliceStable(slice interface{}, less func(i, j int) bool) { 29 rv := reflect.ValueOf(slice) 30 swap := reflect.Swapper(slice) 31 stable_func(lessSwap{less, swap}, rv.Len()) 32 } 33 34 // SliceIsSorted tests whether a slice is sorted. 35 // 36 // The function panics if the provided interface is not a slice. 37 func SliceIsSorted(slice interface{}, less func(i, j int) bool) bool { 38 rv := reflect.ValueOf(slice) 39 n := rv.Len() 40 for i := n - 1; i > 0; i-- { 41 if less(i, i-1) { 42 return false 43 } 44 } 45 return true 46 }