w3resource
Java Programming Exercies

Java Exercises: Gnome sort Algorithm

Java Sorting Algorithm: Exercise-13 with Solution

Write a Java program to sort an array of given integers using Gnome sort Algorithm.

Gnome sort is a sorting algorithm originally proposed by Dr. Hamid Sarbazi-Azad (Professor of Computer Engineering at Sharif University of Technology) in 2000 and called "stupid sort" (not to be confused with bogosort), and then later on described by Dick Grune and named "gnome sort".
The algorithm always finds the first place where two adjacent elements are in the wrong order, and swaps them. It takes advantage of the fact that performing a swap can introduce a new out-of-order adjacent pair only next to the two swapped elements.

A visualization of the gnome sort:

javaScript: gnome sort animation

Sample Solution:

Java Code:

import java.util.Arrays;
class gnomeSort {
 void gnomeSort(int[] nums)
  {
  int i=1;
  int j=2;
 
  while(i < nums.length) {
    if ( nums[i-1] <= nums[i] ) 
	{
      i = j; j++;
    } else {
      int tmp = nums[i-1];
      nums[i-1] = nums[i];
      nums[i--] = tmp;
      i = (i==0) ? j++ : i;
    }
  }
}
  
    // Method to test above
    public static void main(String args[])
    {
        gnomeSort ob = new gnomeSort();
        int nums[] = {7, -5, 3, 2, 1, 0, 45};
        System.out.println("Original Array:");
        System.out.println(Arrays.toString(nums));
        ob.gnomeSort(nums);
        System.out.println("Sorted Array");
        System.out.println(Arrays.toString(nums));
    }
}

Sample Output:

Original Array:
[7, -5, 3, 2, 1, 0, 45]
Sorted Array
[-5, 0, 1, 2, 3, 7, 45]

Flowchart:

Flowchart: Sort an array of given integers using Gnome sort Algorithm.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to sort an array of given integers using CountingSort Algorithm.
Next: Write a Java program to sort an array of given integers using Pancake sort Algorithm.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming