A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python-program-for-gnome-sort/ below:

Python Program for Gnome Sort

Python Program for Gnome Sort

Last Updated : 23 Jul, 2025

In this article we are going to see Gnome Sort with Python.

Algorithm Steps:

                   if (arr[i] >= arr[i-1])
i++;
                       if (arr[i] < arr[i-1])
{
swap(arr[i], arr[i-1]);
i--;
}
Python3
# Python program to implement Gnome Sort

# A function to sort the given list using Gnome sort
def gnomeSort(arr, n):
    index = 0
    while index < n:
        if index == 0:
            index = index + 1
        if arr[index] >= arr[index - 1]:
            index = index + 1
        else:
            arr[index], arr[index - 1] = arr[index - 1], arr[index]
            index = index - 1

    return arr

# Driver Code
arr = [34, 2, 10, -9]
n = len(arr)

arr = gnomeSort(arr, n)
print("Sorted sequence after applying Gnome Sort:", end=" ")
for i in arr:
    print(i, end=" ")

# Contributed By Harshit Agrawal

Output
Sorted sequence after applying Gnome Sort : -9 2 10 34

Time Complexity: O(n2)

Auxiliary Space: O(1)
Please refer complete article on Gnome Sort for more details!
 



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4