diff --git a/README.md b/README.md index f056ffb..49fac2b 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ Algorithms * [heap sort](https://en.wikipedia.org/wiki/Heapsort) * [Shell sort](https://en.wikipedia.org/wiki/Shellsort) * [counting sort](https://en.wikipedia.org/wiki/Counting_sort) + * [radix sort](https://en.wikipedia.org/wiki/Radix_sort) #### Searching diff --git a/sorting/radix_sort.go b/sorting/radix_sort.go new file mode 100644 index 0000000..5ec5432 --- /dev/null +++ b/sorting/radix_sort.go @@ -0,0 +1,47 @@ +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 + } +}