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:
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:
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?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework