gnome sort Algorithm

The gnome sort algorithm, also known as the "stupid sort" or "pathological sort," is a simple sorting algorithm that was invented by Iranian computer scientist Hamid Sarbazi-Azad in 2000. It is a comparison-based sorting algorithm, similar to the bubble sort and insertion sort, but with a few key differences. Gnome sort works by iterating through a list of elements and swapping adjacent elements if they are in the incorrect order. What makes gnome sort unique is that it does not require nested loops or additional data structures, making it easier to understand and implement. The basic idea behind gnome sort is to use a single loop that iterates through the list from left to right. When the algorithm encounters a pair of elements that are out of order, it swaps them and then moves back one position to check if the newly swapped element is in the correct order with respect to its previous elements. This process continues until the entire list is sorted. The name "gnome sort" comes from the idea that a garden gnome sorting a line of flower pots could use this algorithm by comparing the size of the pots and swapping them as necessary, moving back and forth along the line until all the pots are correctly ordered. Gnome sort has a worst-case time complexity of O(n^2), making it inefficient for large datasets, but it can be useful for small or partially sorted lists due to its simplicity and ease of implementation.
"""Gnome Sort Algorithm."""


def gnome_sort(unsorted):
    """Pure implementation of the gnome sort algorithm in Python."""
    if len(unsorted) <= 1:
        return unsorted

    i = 1

    while i < len(unsorted):
        if unsorted[i - 1] <= unsorted[i]:
            i += 1
        else:
            unsorted[i - 1], unsorted[i] = unsorted[i], unsorted[i - 1]
            i -= 1
            if i == 0:
                i = 1


if __name__ == "__main__":
    user_input = input("Enter numbers separated by a comma:\n").strip()
    unsorted = [int(item) for item in user_input.split(",")]
    gnome_sort(unsorted)
    print(unsorted)

LANGUAGE:

DARK MODE: