forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGnomeSort.java
More file actions
73 lines (66 loc) · 1.44 KB
/
GnomeSort.java
File metadata and controls
73 lines (66 loc) · 1.44 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.thealgorithms.sorts;
import static com.thealgorithms.sorts.SortUtils.*;
/**
* Implementation of gnome sort
*
* @author Podshivalov Nikita (https://github.com/nikitap492)
* @since 2018-04-10
*/
public class GnomeSort implements SortAlgorithm {
@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++;
}
}
}
return null;
}
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();
gnomeSort.sort(integers);
gnomeSort.sort(strings);
System.out.println("After sort : ");
print(integers);
print(strings);
}
}