Skip to content
Related Articles

Related Articles

Improve Article

Java Program for Gnome Sort

  • Last Updated : 04 Dec, 2018

Algorithm Steps

  1. If you are at the start of the array then go to the right element (from arr[0] to arr[1]).
  2. 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++;
  1. 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--;
                       }
  1. Repeat steps 2) and 3) till ā€˜iā€™ reaches the end of the array (i.e- ā€˜n-1ā€™)
  2. If the end of the array is reached then stop and the array is sorted.




// 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]

For understanding of Arrays.toString(), Please refer :
https://www.geeksforgeeks.org/arrays-tostring-in-java-with-examples/

Please refer complete article on Gnome Sort for more details!

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :