Java Program for Gnome Sort

Algorithm Steps
- If you are at the start of the array then go to the right element (from arr[0] to arr[1]).
- 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.
Java
// Java Program to implement Gnome Sort Ā
import java.util.Arrays; public class GFG { Ā static void gnomeSort(int arr[], int n) Ā { Ā Ā int index = 0; Ā
Ā Ā while (index < n) { Ā Ā Ā if (index == 0) Ā Ā Ā Ā index++; Ā Ā Ā if (arr[index] >= arr[index - 1]) Ā Ā Ā Ā index++; Ā Ā Ā else { Ā Ā Ā Ā int temp = 0; Ā Ā Ā Ā temp = arr[index]; Ā Ā Ā Ā arr[index] = arr[index - 1]; Ā Ā Ā Ā arr[index - 1] = temp; Ā Ā Ā Ā index--; Ā Ā Ā } Ā Ā } Ā Ā return; Ā } Ā
Ā // Driver program to test above functions. Ā public static void main(String[] args) Ā { Ā Ā int arr[] = { 34, 2, 10, -9 }; Ā
Ā Ā gnomeSort(arr, arr.length); Ā
Ā Ā System.out.print("Sorted sequence after applying Gnome sort: "); Ā Ā System.out.println(Arrays.toString(arr)); Ā } } Ā
// Code Contributed by Mohit Gupta_OMG |
Output:
Sorted sequence after applying Gnome sort: [-9, 2, 10, 34]
Time Complexity: O(n2). As there is no nested loop (only one while) it may seem that this is a linear O(n) time algorithm. But the time complexity is O(n^2) as the variable āindexā in the program doesnāt always get incremented, it gets decremented too.Ā
Auxiliary Space: O(n)
For understanding of Arrays.toString(), Please refer : https://www.zambiatek.com/arrays-tostring-in-java-with-examples/ Please refer complete article on Gnome Sort for more details!
Feeling lost in the world of random DSA topics, wasting time without progress? Itās time for a change! Join our DSA course, where weāll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



