Python Program for Gnome Sort (original) (raw)

Last Updated : 12 Nov, 2025

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:

  1. Start from the first element (index 0).
  2. If at the start of the array, move one step forward.
  3. If the current element is greater than or equal to the previous element, move one step forward.
  4. If the current element is smaller than the previous element, swap both elements and move one step backward.
  5. 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]

  1. Compare 5 and 3, out of order, swap -> [3, 5, 2, 4], move one step back.
  2. At start, move forward.
  3. Compare 5 and 2, out of order, swap -> [3, 2, 5, 4], move one step back.
  4. Compare 3 and 2, out of order, swap -> [2, 3, 5, 4], move one step back.
  5. At start, move forward.
  6. Compare 2 and 3, in order, move forward.
  7. Compare 3 and 5, in order, move forward.
  8. Compare 5 and 4, out of order, swap -> [2, 3, 4, 5], move one step back.
  9. Compare 3 and 4, in order, move forward.

Final sorted list: [2, 3, 4, 5]

Code Implementation:

Python `

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)

`

**Explanation: