Python Example – Write a Python program to sort a list of elements using Gnome sort

Hits: 5

(Python Example for Citizen Data Scientist & Business Analyst)


Write a Python program to sort a list of elements using Gnome sort

Gnome sort is a sorting algorithm originally proposed by Dr. Hamid Sarbazi-Azad (Professor of Computer Engineering at Sharif University of Technology) in 2000 and called “stupid sort” (not to be confused with bogosort), and then later on described by Dick Grune and named “gnome sort”. The algorithm always finds the first place where two adjacent elements are in the wrong order, and swaps them. It takes advantage of the fact that performing a swap can introduce a new out-of-order adjacent pair only next to the two swapped elements.


A visualization of the gnome sort:

Python: gnome sort animation


Sample Solution:

Python Code:

def  gnome_sort(nums):
    if len(nums) <= 1:
        return nums
    i = 1
    while i < len(nums):
        if nums[i-1] <= nums[i]:
            i += 1
            nums[i-1], nums[i] = nums[i], nums[i-1]
            i -= 1
            if (i == 0):
                i = 1
user_input = input("Input numbers separated by a comma:n").strip()
nums = [int(item) for item in user_input.split(',')]

Sample Output:

Input numbers separated by a comma:
 5, 79, 35, 68, 25
[5, 25, 35, 68, 79]


Write a Python program to sort a list of elements using Gnome sort

Sign up to get end-to-end “Learn By Coding” example.

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.