-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathGnomeSort.java
More file actions
35 lines (28 loc) · 758 Bytes
/
GnomeSort.java
File metadata and controls
35 lines (28 loc) · 758 Bytes
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
package Java;
import java.util.Arrays;
public class GnomeSort {
public static void main(String[] args){
int[] arr = {1,6,23,5,8,2,43,35};
System.out.println(Arrays.toString(arr));
gnomeSort(arr);
System.out.println(Arrays.toString(arr));
}
private static void gnomeSort(int[] arr){
int pos = 0;
int size = arr.length;
while(pos < size){
if(pos == 0 || arr[pos] >= arr[pos-1]){
pos ++;
}
else{
swap(arr, pos, pos - 1);
pos--;
}
}
}
private static void swap(int[] arr, int p1, int p2){
int temp = arr[p1];
arr[p1] = arr[p2];
arr[p2] = temp;
}
}