Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added radix sort to the deck of sorting algorithms #23

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
38 changes: 38 additions & 0 deletions RadixSort/RadixSort.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
19 changes: 19 additions & 0 deletions RadixSort/RadixSort_test.go
Original file line number Diff line number Diff line change
@@ -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()
}
}
}