From 5bfeadff65808231fde49ccd1a72dbd5b1213501 Mon Sep 17 00:00:00 2001 From: orthodox-64 <151670745+Orthodox-64@users.noreply.github.com> Date: Thu, 2 Oct 2025 00:24:11 +0530 Subject: [PATCH] chore: added gnome sort algo --- sort/gnomesort.go | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 sort/gnomesort.go diff --git a/sort/gnomesort.go b/sort/gnomesort.go new file mode 100644 index 000000000..b6495ad09 --- /dev/null +++ b/sort/gnomesort.go @@ -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 +} \ No newline at end of file