Skip to content

Commit da115c3

Browse files
committed
feat: add bubble sort
1 parent 03bf913 commit da115c3

File tree

3 files changed

+58
-1
lines changed

3 files changed

+58
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1164,7 +1164,7 @@ list.sort(Comparator.comparingInt(String::length));
11641164

11651165
**Sorting algorithms**
11661166

1167-
- Bubble sort, CLRS#2-problems2.2: [java](/java-algorithm/src/main/java/com/example/algorithm/sort/BubbleSort.java) | Bubble sort is a sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items, and swaps them if needed.<br>($\textit{n}$ is the number of elements)
1167+
- Bubble sort, CLRS#2-problems2.2: [golang](go-algorithm/pkg/sort/bubble_sort.go), [java](/java-algorithm/src/main/java/com/example/algorithm/sort/BubbleSort.java) | Bubble sort is a sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items, and swaps them if needed.<br>($\textit{n}$ is the number of elements)
11681168

11691169
| **Case** | **Time complexity** | **Remarks** |
11701170
| :---------- | :-----------------: | :-------------------------------------------------------------------------------------- |

go-algorithm/pkg/sort/bubble_sort.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package sort
2+
3+
import (
4+
"golang.org/x/exp/constraints"
5+
)
6+
7+
func bubbleSort[T constraints.Integer](arr []T) {
8+
n := len(arr)
9+
for i := 0; i < n; i++ {
10+
for j := n - 1; j > i; j-- {
11+
if arr[j] < arr[j-1] {
12+
arr[j], arr[j-1] = arr[j-1], arr[j]
13+
}
14+
}
15+
}
16+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package sort
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
)
8+
9+
func Test_bubbleSort(t *testing.T) {
10+
type args struct {
11+
arr []int
12+
}
13+
tests := []struct {
14+
name string
15+
args args
16+
want []int
17+
}{
18+
{
19+
name: "Integer Case",
20+
args: args{
21+
arr: []int{31, 64, 49, 85, 71, 26, 6, 19},
22+
},
23+
want: []int{6, 19, 26, 31, 49, 64, 71, 85},
24+
},
25+
{
26+
name: "Empty array input",
27+
args: args{
28+
arr: []int{},
29+
},
30+
want: []int{},
31+
},
32+
}
33+
34+
for _, tt := range tests {
35+
t.Run(tt.name, func(t *testing.T) {
36+
bubbleSort(tt.args.arr)
37+
38+
assert.Equalf(t, tt.want, tt.args.arr, "bubbleSort() got = %v, want %v", tt.args.arr, tt.want)
39+
})
40+
}
41+
}

0 commit comments

Comments
 (0)