<p>
The <code>String</code> method of <code>Sequence</code> is recreating the
-work that <code>Sprint</code> already does for slices. We can share the
-effort if we convert the <code>Sequence</code> to a plain
+work that <code>Sprint</code> already does for slices.
+(It also has complexity O(N²), which is poor.) We can share the
+effort (and also speed it up) if we convert the <code>Sequence</code> to a plain
<code>[]int</code> before calling <code>Sprint</code>.
</p>
<pre>
func (s Sequence) String() string {
+ s = s.Copy()
sort.Sort(s)
return fmt.Sprint([]int(s))
}
// Method for printing - sorts the elements before printing
func (s Sequence) String() string {
+ s = s.Copy()
sort.IntSlice(s).Sort()
return fmt.Sprint([]int(s))
}
s[i], s[j] = s[j], s[i]
}
+// Copy returns a copy of the Sequence.
+func (s Sequence) Copy() Sequence {
+ copy := make(Sequence, 0, len(s))
+ return append(copy, s...)
+}
+
// Method for printing - sorts the elements before printing.
func (s Sequence) String() string {
+ s = s.Copy() // Make a copy; don't overwrite argument.
sort.Sort(s)
str := "["
- for i, elem := range s {
+ for i, elem := range s { // Loop is O(N²); will fix that in next example.
if i > 0 {
str += " "
}