Table of Contents
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
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.
0 Comments