From 671c60bd13355bf6a33a7365d05443492be15ad5 Mon Sep 17 00:00:00 2001 From: Buvanesh11 Date: Mon, 16 Feb 2026 19:00:36 +0530 Subject: [PATCH] Add Gnome Sort implementation in gnome_sort.py Implement Gnome Sort algorithm with time and space complexity details. --- sort/sorting/gnome_sort.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 sort/sorting/gnome_sort.py diff --git a/sort/sorting/gnome_sort.py b/sort/sorting/gnome_sort.py new file mode 100644 index 00000000..856e8f43 --- /dev/null +++ b/sort/sorting/gnome_sort.py @@ -0,0 +1,34 @@ +def gnome_sort(arr): + """ + Gnome Sort Algorithm + + Gnome Sort works similarly to Insertion Sort. + It swaps elements backward until they are in correct order. + + Time Complexity: + Worst & Average: O(n^2) + Best Case: O(n) + + Space Complexity: O(1) + """ + + index = 0 + n = len(arr) + + while index < n: + if index == 0: + index += 1 + elif arr[index] >= arr[index - 1]: + index += 1 + else: + # Swap elements + arr[index], arr[index - 1] = arr[index - 1], arr[index] + index -= 1 + + return arr + + +# Example usage +if __name__ == "__main__": + numbers = [34, 2, 10, 6, 7] + print("Sorted array:", gnome_sort(numbers))