From 228dbff64344353848797adce97534e3d450a572 Mon Sep 17 00:00:00 2001 From: Gourav Suri Date: Sat, 23 Oct 2021 02:10:54 +0530 Subject: [PATCH] added radix sort to the deck of sorting algorithms --- README.md | 1 + RadixSort/RadixSort.go | 38 +++++++++++++++++++++++++++++++++++++ RadixSort/RadixSort_test.go | 19 +++++++++++++++++++ 3 files changed, 58 insertions(+) create mode 100644 RadixSort/RadixSort.go create mode 100644 RadixSort/RadixSort_test.go diff --git a/README.md b/README.md index 90c81b4..213823a 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ There are several data structures and algorithms implemented in this project. Th - Cocktail Sort - Gnome Sort - Merge Sort +- Radix Sort ## Usage diff --git a/RadixSort/RadixSort.go b/RadixSort/RadixSort.go new file mode 100644 index 0000000..657b657 --- /dev/null +++ b/RadixSort/RadixSort.go @@ -0,0 +1,38 @@ +package RadixSort + +import ( + "bytes" + "encoding/binary" +) + +const digit = 4 +const maxbit = -1 << 31 + +func RadixSort(data []int) { + 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] = int(w^maxbit) + } +} diff --git a/RadixSort/RadixSort_test.go b/RadixSort/RadixSort_test.go new file mode 100644 index 0000000..c12188a --- /dev/null +++ b/RadixSort/RadixSort_test.go @@ -0,0 +1,19 @@ +package RadixSort + +import ( + "sort" + "testing" +) + +func TestRadixSort(t *testing.T) { + array1 := []int{421, 15, -175, 90, -2, 214, -52, -166} + array2 := make(sort.IntSlice, len(array1)) + copy(array2, array1) + RadixSort(array1) + array2.Sort() + for i := range array1 { + if array1[i] != array2[i] { + t.Fail() + } + } +}