排序系列【比较排序系列之】直接插入排序 VS shell排序
前两篇分别对直接插入排序和希尔排序分别进行了了解,本篇则分别利用随机值赋值的方式对两个排序进行比较,代码先赋值如下:
直接插入排序代码:
public static void main(String[] args) {
Test2 test2 = new Test2();
int[] array=new int[10];
//随机数赋值,只考虑随机时间
for (int i=0;i<array.length;i++){
array[i]= (int) (Math.random()*1000);
}
long start1 = System.currentTimeMillis();
test2.insertSort(array);
System.out.println("insert sort time: " + (System.currentTimeMillis() - start1));
System.out.println(array.length);
}
void insertSort(int[] array) {
//定义的临时变量
int tempRecord;
//i从1开始的原因是j=j-1
for (int i = 1; i < array.length; i++) {
tempRecord = array[i];
int j = i - 1;
//j不能为负数,根据索引判定值大小,通过临时变量进行交换
while (j >= 0 && tempRecord < array[j]) {
array[j + 1] = array[j];
j = j - 1;
}
array[j + 1] = tempRecord;
}
}
shell排序代码:增量为每次除以2
public static void main(String[] args) {
int[] array=new int[10];
for (int i=0;i<array.length;i++){
array[i]= (int) (Math.random()*1000);
}
long start1 = System.currentTimeMillis();
ShellSort2 shellSort = new ShellSort2();
shellSort.shellSort(array);
System.out.println("shell sort time: " + (System.currentTimeMillis() - start1));
System.out.println(array.length);
}
void shellSort(int[] array) {
int delta;
int n = array.length;
for (delta = n / 2; delta > 0; delta /= 2) {
int tempRecord = 0;
for (int i = delta; i < array.length; i++) {
tempRecord = array[i];
int j = i;
while (j > delta - 1 && tempRecord < array[j - delta]) {
array[j] = array[j - delta];
j -= delta;
}
array[j] = tempRecord;
}
}
}
shell排序代码:增量为每次除以3
public static void main(String[] args) {
int[] array=new int[10];
for (int i=0;i<array.length;i++){
array[i]= (int) (Math.random()*1000);
}
long start1 = System.currentTimeMillis();
ShellSort2 shellSort = new ShellSort2();
shellSort.shellSort(array);
System.out.println("shell sort time: " + (System.currentTimeMillis() - start1));
System.out.println(array.length);
}
void shellSort(int[] array) {
int delta;
int n = array.length;
for (delta = n / 3; delta > 0; delta /= 3) {
int tempRecord = 0;
for (int i = delta; i < array.length; i++) {
tempRecord = array[i];
int j = i;
while (j > delta - 1 && tempRecord < array[j - delta]) {
array[j] = array[j - delta];
j -= delta;
}
array[j] = tempRecord;
}
}
}
最后运行时间见如下表格:
sort | 10 | 100 | 10000 | 100000 | 1000000 | 10000000 |
---|---|---|---|---|---|---|
直接插入排序 | 0(ms) | 0(ms) | 4(ms) | 21(ms) | 1279(ms) | 99052(ms) |
shell排序,增量为2 | 0 | 1 | 1 | 6 | 33 | 177 |
shell排序,增量为3 | 0 | 0 | 1 | 5 | 19 | 158 |
通过对比可得结论:对于shell排序这个专门针对直接插入而诞生的排序而言,其速度确实是快乐许多。