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 Sep 22, 2023
1 parent 676a18d commit 63a5db5
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 1 deletion.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ Solving programming questions from ["Cracking the Coding Interview 6th Edition"]
| 3.2 | [Stack Min][43] | [tests][44] ||
| 3.3 | [Stack of Plates][45] | [tests][46] ||
| 3.4 | [Queue via Stacks][47] | [tests][48] ||
| 3.5 | Sort Stack | tests | |
| 3.5 | [Sort Stack][49] | [tests][50] | |
| 3.6 | Animal Shelter | tests | |

[1]: ch01/01_is_unique.go
Expand Down Expand Up @@ -94,3 +94,5 @@ Solving programming questions from ["Cracking the Coding Interview 6th Edition"]
[46]: ch03/03_stack_of_plates_test.go
[47]: ch03/04_my_queue.go
[48]: ch03/04_my_queue_test.go
[49]: ch03/05_sort_stack.go
[50]: ch03/05_sort_stack_test.go
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 63a5db5

Please sign in to comment.