Skip to content
Open
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
28 changes: 28 additions & 0 deletions sort/gnomesort.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// gnomesort.go
// description: Implementation of gnome sort algorithm
// worst-case time complexity: O(n^2)
// average-case time complexity: O(n^2)
// best-case time complexity: O(n) (if nearly sorted)
// space complexity: O(1)

package sort

import "github.com/TheAlgorithms/Go/constraints"

// GnomeSort sorts the slice using the gnome sort algorithm
func Gnome[T constraints.Ordered](arr []T) []T {
i := 1
n := len(arr)
for i < n {
// If at start or current element is in correct order relative to previous
if i == 0 || arr[i] >= arr[i-1] {
i++ // move forward
} else {
// swap arr[i] and arr[i-1]
arr[i], arr[i-1] = arr[i-1], arr[i]
// move back one position
i--
}
}
return arr
}