go1_1.go 711 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. // Copyright 2013 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. //go:build !go1.2
  5. // +build !go1.2
  6. package language
  7. import "sort"
  8. func sortStable(s sort.Interface) {
  9. ss := stableSort{
  10. s: s,
  11. pos: make([]int, s.Len()),
  12. }
  13. for i := range ss.pos {
  14. ss.pos[i] = i
  15. }
  16. sort.Sort(&ss)
  17. }
  18. type stableSort struct {
  19. s sort.Interface
  20. pos []int
  21. }
  22. func (s *stableSort) Len() int {
  23. return len(s.pos)
  24. }
  25. func (s *stableSort) Less(i, j int) bool {
  26. return s.s.Less(i, j) || !s.s.Less(j, i) && s.pos[i] < s.pos[j]
  27. }
  28. func (s *stableSort) Swap(i, j int) {
  29. s.s.Swap(i, j)
  30. s.pos[i], s.pos[j] = s.pos[j], s.pos[i]
  31. }