Skip to content

Commit 1289e69

Browse files
authored
bubble sort (#78)
1 parent 6b1a87f commit 1289e69

File tree

5 files changed

+43
-1
lines changed

5 files changed

+43
-1
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ Welcome to **Data Structures and Algorithms in Go**! 🎉 This project is design
2525
* Product of All Other Elements
2626
* Equal Sum Sub-arrays
2727
* Rotate K Steps
28+
* Bubble Sort
2829
* [Strings](./strings)
2930
* The longest Dictionary Word Containing Key
3031
* Look and Tell

array/README.md

+4
Original file line numberDiff line numberDiff line change
@@ -113,3 +113,7 @@ Given an array of integers A, return two sub-arrays with equal sums without chan
113113
### Rotate K Steps
114114

115115
Given an array of integers and a number k, rotate the array k times. [Solution](rotate_k_steps.go), [Tests](rotate_k_steps_test.go)
116+
117+
### Bubble Sort
118+
119+
Given an array of unsorted integers, sort the array using the Bubble Sort algorithm, where each element is repeatedly compared with the next element and swapped if needed. [Solution](bubble_sort.go), [Tests](bubble_sort_test.go)

array/bubble_sort.go

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package array
2+
3+
// BubbleSort implements the Bubble Sort algorithm.
4+
func BubbleSort(input []int) {
5+
for i := range input {
6+
for j := range input {
7+
if input[i] < input[j] {
8+
input[i], input[j] = input[j], input[i]
9+
}
10+
}
11+
}
12+
}

array/bubble_sort_test.go

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package array
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
func TestBubbleSort(t *testing.T) {
9+
tests := []struct {
10+
input, sorted []int
11+
}{
12+
{[]int{}, []int{}},
13+
{[]int{1}, []int{1}},
14+
{[]int{1, 2}, []int{1, 2}},
15+
{[]int{2, 1}, []int{1, 2}},
16+
{[]int{2, 3, 1}, []int{1, 2, 3}},
17+
{[]int{4, 2, 3, 1, 5}, []int{1, 2, 3, 4, 5}},
18+
}
19+
for i, test := range tests {
20+
BubbleSort(test.input)
21+
if !reflect.DeepEqual(test.input, test.sorted) {
22+
t.Fatalf("Failed test case #%d. Want %v got %v", i, test.sorted, test.input)
23+
}
24+
}
25+
}

complexity.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ The time complexity of O(n log n) is commonly observed when it is necessary to i
114114

115115
Polynomial time complexity marks the initial threshold of problematic time complexity for algorithms. This complexity often arises when an algorithm includes nested loops, involving both an inner loop and an outer loop. Examples:
116116

117-
* Bobble sort rehearsal problem in [array](../array)
117+
* Bubble sort rehearsal problem in [array](../array)
118118
* Naive way of searching an unsorted [array](../array) for duplicates by using nested loops
119119

120120
### Exponential O(2^n)

0 commit comments

Comments
 (0)