🚧 Add Defrag function
This commit is contained in:
parent
2f165369cc
commit
932e8e2f11
7 changed files with 136 additions and 1 deletions
26
defrag.go
Normal file
26
defrag.go
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
package defrag
|
||||
|
||||
// Defrag performs an in-place sort of blocks.
|
||||
// If an error occurs during processing, it will be returned. The slice may have been partially sorted.
|
||||
func Defrag(blocks []byte) error {
|
||||
lastPulled := len(blocks)
|
||||
lastPushed := -1
|
||||
for block := 0; block < len(blocks); block++ {
|
||||
if blocks[block] != '.' {
|
||||
continue
|
||||
}
|
||||
if lastPulled <= block {
|
||||
break
|
||||
}
|
||||
for swap := lastPulled - 1; swap > lastPushed; swap-- {
|
||||
if blocks[swap] == '.' {
|
||||
continue
|
||||
}
|
||||
blocks[block], blocks[swap] = blocks[swap], blocks[block]
|
||||
lastPulled = swap
|
||||
lastPushed = block
|
||||
break
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue