Skip to content

Commit

Permalink
shell sort
Browse files Browse the repository at this point in the history
  • Loading branch information
giovannymassuia committed Jun 28, 2024
1 parent 07311b6 commit a6d641f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
27 changes: 27 additions & 0 deletions go-dsa/sorting/shell_sort.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package sorting

type ShellSort struct{}

func (i *ShellSort) Sort(arr []int) {
// 1. start with a large gap, then reduce the gap until it becomes 1
// 2. perform insertion sort on the elements with the gap

for gap := len(arr) / 2; gap > 0; gap /= 2 {
// start from the gap element and move to the right
for i := gap; i < len(arr); i++ {
// store the current element
temp := arr[i]
j := i

// run the insertion sort on the elements with the gap
// shift the elements to the right until the correct position is found
for j >= gap && arr[j-gap] > temp {
arr[j] = arr[j-gap]
j -= gap
}

// insert the temp element at the correct position
arr[j] = temp
}
}
}
1 change: 1 addition & 0 deletions go-dsa/sorting/sorting_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ func TestSorting(t *testing.T) {
algorithms := []Sorting{
&InsertionSort{},
&HeapSort{},
&ShellSort{},
}

tests := buildTestData()
Expand Down

0 comments on commit a6d641f

Please sign in to comment.