2018-11-14 01:15:47 +08:00
|
|
|
package Sorts;
|
2018-04-10 16:32:49 +08:00
|
|
|
|
2018-11-14 01:15:47 +08:00
|
|
|
import static Sorts.SortUtils.*;
|
2018-04-10 16:32:49 +08:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Implementation of gnome sort
|
|
|
|
*
|
|
|
|
* @author Podshivalov Nikita (https://github.com/nikitap492)
|
|
|
|
* @since 2018-04-10
|
2020-10-24 18:23:28 +08:00
|
|
|
*/
|
2019-05-09 19:32:54 +08:00
|
|
|
public class GnomeSort implements SortAlgorithm {
|
2018-04-10 16:32:49 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
@Override
|
|
|
|
public <T extends Comparable<T>> T[] sort(T[] arr) {
|
|
|
|
int i = 1;
|
|
|
|
int j = 2;
|
|
|
|
while (i < arr.length) {
|
|
|
|
if (less(arr[i - 1], arr[i])) i = j++;
|
|
|
|
else {
|
|
|
|
swap(arr, i - 1, i);
|
|
|
|
if (--i == 0) {
|
|
|
|
i = j++;
|
2018-04-10 16:32:49 +08:00
|
|
|
}
|
2020-10-24 18:23:28 +08:00
|
|
|
}
|
2018-04-10 16:32:49 +08:00
|
|
|
}
|
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
return null;
|
|
|
|
}
|
2018-04-10 16:32:49 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
public static void main(String[] args) {
|
|
|
|
Integer[] integers = {4, 23, 6, 78, 1, 26, 11, 23, 0, -6, 3, 54, 231, 9, 12};
|
|
|
|
String[] strings = {"c", "a", "e", "b", "d", "dd", "da", "zz", "AA", "aa", "aB", "Hb", "Z"};
|
|
|
|
GnomeSort gnomeSort = new GnomeSort();
|
2018-04-10 16:32:49 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
gnomeSort.sort(integers);
|
|
|
|
gnomeSort.sort(strings);
|
2018-04-10 16:32:49 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
System.out.println("After sort : ");
|
|
|
|
print(integers);
|
|
|
|
print(strings);
|
|
|
|
}
|
2018-04-10 16:32:49 +08:00
|
|
|
}
|