Skip to content

Commit

Permalink
Merge pull request #29 from gabrielperes97/GnomeSort
Browse files Browse the repository at this point in the history
Implemented Gnome sort algorithm - Issue #1
  • Loading branch information
diptangsu authored Oct 26, 2018
2 parents d3e5010 + 0d66766 commit afe9a84
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 1 deletion.
4 changes: 4 additions & 0 deletions src/AlgorithmComparison.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ private static void compareSortingAlgorithms(int arr[]) {
printSortingTime(SortType.SELECTION, arr);
printSortingTime(SortType.CYCLE, arr);
printSortingTime(SortType.SHELL, arr);
printSortingTime(SortType.GNOME, arr);
}

private static void printSortingTime(SortType sortType, int[] arr) {
Expand Down Expand Up @@ -77,6 +78,9 @@ private static void printSortingTime(SortType sortType, int[] arr) {
case SHELL:
ShellSort.shellSort(arr2);
break;
case GNOME:
GnomeSort.gnomeSort(arr2);
break;
}

long endTime = System.nanoTime();
Expand Down
57 changes: 57 additions & 0 deletions src/GnomeSort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,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;
}
}
3 changes: 2 additions & 1 deletion src/SortType.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ public enum SortType {
SELECTION,
CYCLE,
SHELL,
COMB
COMB,
GNOME
}

0 comments on commit afe9a84

Please sign in to comment.