-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
72 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
package ch03 | ||
|
||
// Sort stack in ascending order (min values on top) | ||
// Use temporary stack to sort values in descending | ||
// order. Then reverse it into original stack. | ||
func Sort(stack *Stack) { | ||
sorted := new(Stack) | ||
|
||
// fill in sorted stack in descending order | ||
for !stack.IsEmpty() { | ||
tmp, _ := stack.Pop() | ||
|
||
for !sorted.IsEmpty() { | ||
top, _ := sorted.Peek() | ||
if top < tmp { | ||
break | ||
} | ||
|
||
top, _ = sorted.Pop() | ||
stack.Push(top) | ||
} | ||
|
||
sorted.Push(tmp) | ||
} | ||
|
||
// reverse sorted stack | ||
for !sorted.IsEmpty() { | ||
top, _ := sorted.Pop() | ||
stack.Push(top) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
package ch03 | ||
|
||
import "testing" | ||
|
||
func TestSort(t *testing.T) { | ||
type args struct { | ||
stack *Stack | ||
values []int | ||
} | ||
tests := []struct { | ||
name string | ||
args args | ||
want []int | ||
}{ | ||
{ | ||
name: "sorts random stack", | ||
args: args{stack: new(Stack), values: []int{1, 2, 3, 4, 10}}, | ||
want: []int{1, 2, 3, 4, 10}, | ||
}, | ||
{ | ||
name: "sorts a stack that already sorted", | ||
args: args{stack: new(Stack), values: []int{5, 4, 3, 2, 1}}, | ||
want: []int{1, 2, 3, 4, 5}, | ||
}, | ||
} | ||
for _, tt := range tests { | ||
t.Run(tt.name, func(t *testing.T) { | ||
stack := tt.args.stack | ||
for _, v := range tt.args.values { | ||
stack.Push(v) | ||
} | ||
Sort(stack) | ||
for _, want := range tt.want { | ||
got, _ := stack.Pop() | ||
if got != want { | ||
t.Errorf("Sorted stack Pop() got = %v, want %v", got, want) | ||
} | ||
} | ||
}) | ||
} | ||
} |