mirror of
https://github.com/cubixle/playground.git
synced 2026-04-24 18:34:44 +01:00
finish sorted queue
This commit is contained in:
@@ -1,6 +1,9 @@
|
||||
package queue
|
||||
|
||||
import "sync"
|
||||
import (
|
||||
"log"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type Item struct {
|
||||
ID string
|
||||
@@ -36,16 +39,22 @@ func (q *queue) Put(r *Item) bool {
|
||||
|
||||
q.queue = append(q.queue, r)
|
||||
|
||||
if len(q.queue) > 0 {
|
||||
// sort the queue
|
||||
for i := len(q.queue); i > 0; i-- {
|
||||
if q.queue[i].Priority > q.queue[i-1].Priority {
|
||||
q.queue[i] = q.queue[i-1]
|
||||
q.queue[i-1] = q.queue[i]
|
||||
}
|
||||
qu := q.queue
|
||||
i := 1
|
||||
for i < len(qu) {
|
||||
j := i
|
||||
for j >= 1 && qu[j].Priority > qu[j-1].Priority {
|
||||
tmp := qu[j-1]
|
||||
qu[j-1] = qu[j]
|
||||
qu[j] = tmp
|
||||
|
||||
j--
|
||||
}
|
||||
i++
|
||||
}
|
||||
|
||||
q.queue = qu
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -67,3 +76,9 @@ func (q *queue) GetNext() *Item {
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
func (q *queue) Display() {
|
||||
for _, i := range q.queue {
|
||||
log.Println(i)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,15 +18,18 @@ func TestQueue(t *testing.T) {
|
||||
t.Fatal("didn't get a item")
|
||||
}
|
||||
if v.ID != "bbb" {
|
||||
t.Fatal("id wasn't what we expected")
|
||||
t.Fatalf("id wasn't what we expected bbb, got %s", v.ID)
|
||||
}
|
||||
v = q.GetNext()
|
||||
if v.ID != "aaa" {
|
||||
t.Fatal("id wasn't what we expected")
|
||||
t.Fatalf("id wasn't what we expected aaa, got %s", v.ID)
|
||||
}
|
||||
v = q.GetNext()
|
||||
if v.ID != "ccc" {
|
||||
t.Fatal("id wasn't what we expected")
|
||||
t.Fatalf("id wasn't what we expected ccc, got %s", v.ID)
|
||||
}
|
||||
v = q.GetNext()
|
||||
if v.ID != "ddd" {
|
||||
t.Fatal("id wasn't what we expected")
|
||||
t.Fatalf("id wasn't what we expected ddd, got %s", v.ID)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user