- Related Questions & Answers
- C Program for Tower of Hanoi
- C++ Program for Dijkstra’s shortest path algorithm?
- C/C++ Program for nth Catalan Number?
- C Program to Multiply two Floating Point Numbers?
- C program to find the length of a string?
- C Program to Check if all digits of a number divide it
- C Program to Check if a Given String is a Palindrome?
- Write a program to Delete a Tree in C programming
- Write a C program to print “ Tutorials Point ” without using a semicolon
- Sum of the nodes of a Singly Linked List in C Program
- Sum of first n natural numbers in C Program
- C Program for simple interest?
- Area of a n-sided regular polygon with given Radius in C Program?
- Area of a leaf inside a square in C Program?
- C Program for Area of a square inscribed in a circle which is inscribed in a hexagon?

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

In this article, we will learn about the solution to the problem statement given below.

**Problem statement** − We are given an array, we need to sort it using gnome sort.

1. Firstly we traverse the array from left to right. 2. Now,if the current element is larger or equal to the previous element then we traverse one step ahead 3. otherwise,if the current element is smaller than the previous element then swap these two elements and traverse one step back. 4. Repeat steps given above till we reach the end of the array

Now let’s observe the solution in the implementation below −

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 # main arr = [1,4,2,3,6,5,8,7] n = len(arr) arr = gnomeSort(arr, n) print ("Sorted sequence is:") for i in arr: print (i,end=" ")

Sorted sequence is: 1 2 3 4 5 6 7 8

All the variables are declared in the local scope and their references are seen in the figure above.

In this article, we have learned about how we can make a Python Program for Gnome Sort

Advertisements