mirror of
https://github.com/cubixle/playground.git
synced 2026-04-24 23:04:41 +01:00
finish sorted queue
This commit is contained in:
@@ -1,6 +1,9 @@
|
|||||||
package queue
|
package queue
|
||||||
|
|
||||||
import "sync"
|
import (
|
||||||
|
"log"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
type Item struct {
|
type Item struct {
|
||||||
ID string
|
ID string
|
||||||
@@ -36,16 +39,22 @@ func (q *queue) Put(r *Item) bool {
|
|||||||
|
|
||||||
q.queue = append(q.queue, r)
|
q.queue = append(q.queue, r)
|
||||||
|
|
||||||
if len(q.queue) > 0 {
|
qu := q.queue
|
||||||
// sort the queue
|
i := 1
|
||||||
for i := len(q.queue); i > 0; i-- {
|
for i < len(qu) {
|
||||||
if q.queue[i].Priority > q.queue[i-1].Priority {
|
j := i
|
||||||
q.queue[i] = q.queue[i-1]
|
for j >= 1 && qu[j].Priority > qu[j-1].Priority {
|
||||||
q.queue[i-1] = q.queue[i]
|
tmp := qu[j-1]
|
||||||
}
|
qu[j-1] = qu[j]
|
||||||
|
qu[j] = tmp
|
||||||
|
|
||||||
|
j--
|
||||||
}
|
}
|
||||||
|
i++
|
||||||
}
|
}
|
||||||
|
|
||||||
|
q.queue = qu
|
||||||
|
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -67,3 +76,9 @@ func (q *queue) GetNext() *Item {
|
|||||||
|
|
||||||
return r
|
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")
|
t.Fatal("didn't get a item")
|
||||||
}
|
}
|
||||||
if v.ID != "bbb" {
|
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" {
|
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" {
|
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" {
|
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