-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathShellSort.java
36 lines (28 loc) · 867 Bytes
/
ShellSort.java
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
package algorithms.sort;
/**
* UnStable sort
* time: O(n^2) Quadratic Time(could be better depending on the Gap)
* in-place Algorithm
*/
public class ShellSort {
public static int[] shellSort(int[] arr) {
for (int gap = arr.length / 2; gap > 0; gap /= 2) {
for (int i = gap; i < arr.length; i++) {
int newElement = arr[i];
int j;
for (j = i; j >= gap && arr[j - gap] > newElement; j -= gap) {
arr[j] = arr[j - gap];
}
arr[j] = newElement;
}
}
return arr;
}
public static void main(String[] args) {
int[] arr = {23, 435, 5, 6, 88, 99, -32, 4, -665};
int[] sortedArray = shellSort(arr);
for (int item : sortedArray) {
System.out.println(item);
}
}
}