Skip to content

Commit 79feb13

Browse files
Adding BucketSort
1 parent 302f50a commit 79feb13

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed

Go/sorting/bucketsort.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/*
2+
Bucket sort is mainly useful when input is uniformly distributed over a range. (Floating point nos)
3+
*/
4+
5+
package sorting
6+
7+
func BucketSort(arr []float64) {
8+
n := len(arr)
9+
noOfBuckets := 10.0
10+
bucket := make([][]float64, 10)
11+
12+
//Step 1 : Put the elements into their respective bucket by multiplying it with 10. Each bucket of size 0.1
13+
for i := 0; i < n; i++ {
14+
bucketNo := int(arr[i] * noOfBuckets)
15+
bucket[bucketNo] = append(bucket[bucketNo], arr[i])
16+
}
17+
18+
//Step 2: Insertion sort on each bucket
19+
for i := 0; i < 10; i++ {
20+
insertionSortFloat(bucket[i], len(bucket[i]))
21+
}
22+
23+
pointer := 0
24+
for bucketNo := 0; bucketNo < 10; bucketNo++ {
25+
for index := 0; index < len(bucket[bucketNo]); index++ {
26+
arr[pointer] = bucket[bucketNo][index]
27+
pointer++
28+
}
29+
}
30+
}
31+
32+
func insertionSortFloat(arr []float64, n int) {
33+
for i := 1; i < n; i++ {
34+
hole := arr[i]
35+
j := i
36+
37+
for j > 0 && hole < arr[j-1] {
38+
arr[j] = arr[j-1]
39+
j--
40+
}
41+
42+
arr[j] = hole
43+
}
44+
}

Go/sorting/bucketsort_test.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/*
2+
Bucket sort is mainly useful when input is uniformly distributed over a range. (Floating point nos)
3+
*/
4+
5+
package sorting
6+
7+
import (
8+
"reflect"
9+
"testing"
10+
)
11+
12+
func TestBucketSort(t *testing.T) {
13+
type args struct {
14+
arr []float64
15+
}
16+
tests := []struct {
17+
name string
18+
args args
19+
want []float64
20+
}{
21+
{
22+
name: "test-01",
23+
args: args{
24+
arr: []float64{0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434},
25+
},
26+
want: []float64{0.1234, 0.3434, 0.565, 0.656, 0.665, 0.897},
27+
},
28+
}
29+
for _, tt := range tests {
30+
t.Run(tt.name, func(t *testing.T) {
31+
BucketSort(tt.args.arr)
32+
if !reflect.DeepEqual(tt.args.arr, tt.want) {
33+
t.Errorf("Got:%v but want:%v", tt.args.arr, tt.want)
34+
}
35+
})
36+
}
37+
}

0 commit comments

Comments
 (0)