-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShellSort.java
More file actions
34 lines (31 loc) · 1.12 KB
/
ShellSort.java
File metadata and controls
34 lines (31 loc) · 1.12 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
package basic.sort;
import org.junit.Test;
import utils.ArrayUtils;
import java.util.Arrays;
/**希尔排序,基于简单插入的改动
* 时间复杂度取决于gap的选择,当gap取1时就退化为了插入排序
* 插入排序在数据基本有序时效率很高,而希尔排序可以在分组之后达到基本有序的状态,所以时间复杂度会有下降
* 时间复杂度 O(n^(1.3—2))
* @author JunjunYang
* @date 2020/4/13 20:11
*/
public class ShellSort implements IArraySort{
@Test
public void test() {
System.out.println(Arrays.toString(sort(new int[]{5,4,3,6,8,1,7})));
}
@Override
public int[] sort(int[] sourceArray) {
for (int gap=sourceArray.length/2;gap>0;gap=gap/2) {
for (int i=gap;i<sourceArray.length;i++) {
int j=i;
//循环与同组的进行比较
while (j-gap>=0 && sourceArray[j]<sourceArray[j-gap]) {
ArrayUtils.swap(sourceArray,j,j-gap);
j-=gap;
}
}
}
return sourceArray;
}
}