Java Program for Gnome Sort

Gnome Sort works with one lement at a time and gets it to the actual position. Let us see an example to implement Gnome Sort −


 Live Demo

import java.util.Arrays;
public class Demo{
   static void gnome_sort(int my_arr[], int n){
      int index = 0;
      while (index < n){
         if (index == 0)
         if (my_arr[index] >= my_arr[index - 1])
            int temp = 0;
            temp = my_arr[index];
            my_arr[index] = my_arr[index - 1];
            my_arr[index - 1] = temp;
   public static void main(String[] args){
      int my_arr[] = { 34, 67, 89, 11, 0 , -21 };
      gnome_sort(my_arr, my_arr.length);
      System.out.println("The array after perfroming gnome sort on it is ");


The array after perfroming gnome sort on it is
[-21, 0, 11, 34, 67, 89]

A class named Demo contains a static function named ‘gnome_sort’. Here, a variable ‘index’ is assigned to 0. If that index value is less than the length of the array, the index value is checked for 0. If it is 0, it is incremented by 1. Otherwise, if the value at a specific index is greater than the value at array’s ‘index-1’, a variable named ‘temp’ is assigned 0 and the elements are swapped. The ‘index’ value is decremented.

In the main function, an array is defined with certain values and the ‘gnome_sort’ function is called on this array and the length of the array. The output is printed on the console.

Updated on: 07-Jul-2020


Kickstart Your Career

Get certified by completing the course

Get Started