public class InsSort {
public int[] insSort(int[] array) {
int temp;
int j;
for(int i=1;i<array.length;i++) {
temp = array[i];
j = i;
while(j>0 && array[j-1]>temp) {
array[j] = array[j-1];
j--;
}
array[j] = temp;
}
return array;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
3.时间空间效率 (最好情况为:顺序排列;最坏情况为:逆序排列;)
时间复杂度:
T(n)=O(n2)
空间复杂度:
S(n)=O(1)
- 希尔排序
1.算法思想:希尔排序又称为缩小增量排序,利用了直接插入排序的最佳性质。将初序列分成若干较小的子序列,对子序列进行直接插入排序。
2.代码实现:
public class ShellSort {
public int[] shellInsertSort(int[] array,int delta) {
for(int i=delta;i<array.length;i++) {
if(array[i-delta] > array[i]) {
int j = i-delta;
int temp = array[i];
array[i] = array[i-delta];
while(j>=0 && array[j]>temp) {
array[j+delta] = array[j];
j = j-delta;
}
array[j+delta] = temp;
}
}
return array;
}
public int[] shellSort(int[] array,int initDelta) {
while(initDelta>=1) {
array = shellInsertSort(array,initDelta);
initDelta = initDelta/2;
}
return array;
}
}
- 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
3.时间空间效率:
时间复杂度:
T(n)=O(n1.5)
空间复杂度:
S(n)=O(1)
**注意:希尔排序对于中等规模(n<=1000)的序列具有较高的效率。
希尔排序不稳定,反例{2,4,1,2}**
-
测试代码
public class Main {
public static void main(String[] args) {
int[] arrayIn = {12,2,32,3,9,15,56,78,34,99,21};
ShellSort shell = new ShellSort();
int[] arrayOut = shell.shellSort(arrayIn, arrayIn.length/2);
output(arrayOut);
}
public static void output(int[] array) {
for(int i=0;i<array.length;i++) {
System.out.print(array[i] + " ");
}
}
}