# Python Program for Gnome Sort

In this article we are going to see Gnome Sort with Python.

Algorithm Steps:

• If you are at the start of the array then go to the right element (from arr to arr).
• If the current array element is larger or equal to the previous array element then go one step right
`                   if (arr[i] >= arr[i-1])                      i++;`
• If the current array element is smaller than the previous array element then swap these two elements and go one step backwards
`                       if (arr[i] < arr[i-1])                       {                           swap(arr[i], arr[i-1]);                           i--;                       }`
• Repeat steps 2) and 3) till ‘i’ reaches the end of the array (i.e- ‘n-1’)
• If the end of the array is reached then stop and the array is sorted.

## Python3

 `# Python program to implement Gnome Sort`   `# A function to sort the given list using Gnome sort` `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`   `# Driver Code` `arr ``=` `[``34``, ``2``, ``10``, ``-``9``]` `n ``=` `len``(arr)`   `arr ``=` `gnomeSort(arr, n)` `print``(``"Sorted sequence after applying Gnome Sort:"``, end``=``" "``)` `for` `i ``in` `arr:` `    ``print``(i, end``=``" "``)`   `# Contributed By Harshit Agrawal`

Output

```Sorted sequence after applying Gnome Sort : -9 2 10 34
```

Time Complexity: O(n2)

Auxiliary Space: O(1)
Please refer complete article on Gnome Sort for more details!

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Previous
Next