-
Notifications
You must be signed in to change notification settings - Fork 1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
ashishkrishan1995
committed
Oct 6, 2018
1 parent
755be61
commit 29ab3d1
Showing
1 changed file
with
49 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
// Radix Sort in Golang | ||
package main | ||
|
||
import ( | ||
"bytes" | ||
"encoding/binary" | ||
"fmt" | ||
) | ||
|
||
const digit = 4 | ||
const maxbit = -1 << 31 | ||
|
||
|
||
func main() { | ||
|
||
var data = []int32{421, 15, -175, 90, -2, 214, -52, -166} | ||
fmt.Println("\n--- Unsorted --- \n\n", data) | ||
radixsort(data) | ||
fmt.Println("\n--- Sorted ---\n\n", data, "\n") | ||
} | ||
|
||
func radixsort(data []int32) { | ||
buf := bytes.NewBuffer(nil) | ||
ds := make([][]byte, len(data)) | ||
for i, e := range data { | ||
binary.Write(buf, binary.LittleEndian, e^maxbit) | ||
b := make([]byte, digit) | ||
buf.Read(b) | ||
ds[i] = b | ||
} | ||
countingSort := make([][][]byte, 256) | ||
for i := 0; i < digit; i++ { | ||
for _, b := range ds { | ||
countingSort[b[i]] = append(countingSort[b[i]], b) | ||
} | ||
j := 0 | ||
for k, bs := range countingSort { | ||
copy(ds[j:], bs) | ||
j += len(bs) | ||
countingSort[k] = bs[:0] | ||
} | ||
} | ||
var w int32 | ||
for i, b := range ds { | ||
buf.Write(b) | ||
binary.Read(buf, binary.LittleEndian, &w) | ||
data[i] = w^maxbit | ||
} | ||
} |