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