Program for Gnome Sort using Python

Introduction

Our task is to sort the given array element using gnome sort algorithm.

Program

def sort(array, n):

    i = 0

    while i < n:

        if i == 0:

            i = i + 1

        if array[i] >= array[i - 1]:

            i = i + 1

        else:

            array[i], array[i-1] = array[i-1], array[i]

            i = i - 1

    return array

ip_arr = [81, 2, 101, 6, 51]

sort(ip_arr, len(ip_arr))

print("The sorted array is :")

for i in range(0, len(ip_arr)):

    print(ip_arr[i])

Output

Program for Gnome Sort using Python

Explanation

The steps followed in the above program are:

  • Traverse the element from index 0 to 1. If the element is larger and equal to the previous element, move ahead one step right.
  • If the current element is smaller than the previous element, swap the elements and move one step backward.
  • Repeat the above steps for all the elements and return the sorted array.

Author

  • Barry Allen

    A Full Stack Developer with 10+ years of experience in different domain including SAP, Blockchain, AI and Web Development.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.