Gnome Sort is a simple comparison-based algorithm similar to Insertion Sort. It repeatedly swaps adjacent elements if they are out of order and moves backward until all elements are correctly placed.
Algorithm Steps:
- Start from the first element (index 0).
- If at the start of the array, move one step forward.
- If the current element is greater than or equal to the previous element, move one step forward.
- If the current element is smaller than the previous element, swap both elements and move one step backward.
- Repeat steps 2-4 until the end of the array is reached.
Illustration of Gnome Sort
Let’s take an example: Input: [5, 3, 2, 4]
- Compare 5 and 3, out of order, swap -> [3, 5, 2, 4], move one step back.
- At start, move forward.
- Compare 5 and 2, out of order, swap -> [3, 2, 5, 4], move one step back.
- Compare 3 and 2, out of order, swap -> [2, 3, 5, 4], move one step back.
- At start, move forward.
- Compare 2 and 3, in order, move forward.
- Compare 3 and 5, in order, move forward.
- Compare 5 and 4, out of order, swap -> [2, 3, 4, 5], move one step back.
- Compare 3 and 4, in order, move forward.
Final sorted list: [2, 3, 4, 5]
Code Implementation:
def gnomeSort(arr, n):
ind = 0
while ind < n:
if ind == 0:
ind += 1
if arr[ind] >= arr[ind - 1]:
ind += 1
else:
arr[ind], arr[ind - 1] = arr[ind - 1], arr[ind]
ind -= 1
return arr
arr = [34, 2, 10, -9]
n = len(arr)
arr = gnomeSort(arr, n)
print( *arr)
Output
-9 2 10 34
Explanation:
- ind = 0: Initialize the starting position at the first element.
- while ind < n: Continue the loop until the entire list is traversed.
- if ind == 0: If we are at the start, move one step forward since there’s nothing to compare.
- if arr[ind] >= arr[ind- 1]: If the current element is in correct order with the previous one, move forward.
- else: If the elements are out of order, swap them.
- arr[index], arr[index - 1] = arr[index - 1], arr[index]: Swap adjacent elements that are not in order.
- index -= 1: After swapping, move one step back to recheck the order.
- return arr: Once all elements are in the correct order, return the sorted list.