You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

39 lines
693 B

  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. }