forked from JCarlosR/Sorting-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGnomeSort.java
More file actions
57 lines (49 loc) · 1.75 KB
/
GnomeSort.java
File metadata and controls
57 lines (49 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.util.Random;
/*
Gnome Sort is based on the technique used by the standard Dutch Garden Gnome (Du.: tuinkabouter).
Here is how a garden gnome sorts a line of flower pots.
Basically, he looks at the flower pot next to him and the previous one; if they are in the right order he steps one pot forward, otherwise, he swaps them and steps one pot backward.
Boundary conditions: if there is no previous pot, he steps forwards; if there is no pot next to him, he is done.
— "Gnome Sort - The Simplest Sort Algorithm". Dickgrune.com
*/
public class GnomeSort {
public static void main(String args[])
{
System.out.println("Sorting of randomly generated numbers using GNOME SORT");
Random random = new Random();
int N = 20;
int[] sequence = new int[N];
for (int i = 0; i < N; i++)
sequence[i] = Math.abs(random.nextInt(100));
System.out.println("\nOriginal Sequence: ");
printSequence(sequence);
System.out.println("\nSorted Sequence: ");
printSequence(gnomeSort(sequence));
}
static void printSequence(int[] sortedSequence)
{
for (int i = 0; i < sortedSequence.length; i++)
System.out.print(sortedSequence[i] + " ");
}
public static int[] gnomeSort(int arr[]){
int first = 1;
while(first < arr.length)
{
if (arr[first-1] <= arr[first])
{
first++;
}
else
{
int tmp = arr[first-1];
arr[first - 1] = arr[first];
arr[first] = tmp;
if (-- first == 0)
{
first = 1;
}
}
}
return arr;
}
}