Skip to content

Commit

Permalink
#1 3.5 Sort Stack implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
krlv committed Apr 26, 2021
1 parent c701e0b commit 2e1d1c4
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
31 changes: 31 additions & 0 deletions ch03/05_sort_stack.go
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)
}
}
41 changes: 41 additions & 0 deletions ch03/05_sort_stack_test.go
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)
}
}
})
}
}

0 comments on commit 2e1d1c4

Please sign in to comment.