希爾排序的Java實現、效能分析以及適用場景
阿新 • • 發佈:2018-12-23
1.希爾排序的Java實現:
程式碼如下:
package com.zm.testSort;
/**
*希爾排序的最優化
* @author zm
*/
public class ShellSort {
public static void getShellSort(int[] a) {
int n = a.length;
if(a == null || n == 0) {
System.out.println("該陣列為空!");
return;
}
int d = 1 ;
while(d <= n/3) {//間隔序列函式 d = d * 3 + 1 : 1, 4, 13 等等
d = d*3 + 1;//獲取最大的間隔序列
}
while(d > 0) {
int temp;
for(int i = d; i < n; i++) {//進行直接插入排序
temp = a[i];
int j = i-d;
for(; j >= 0 && a[j] > temp; j = j-d) {
a[j+d] = a[j];
}
a[j+d] = temp;
}
d = (d-1 )/3;//縮減間隔序列
}
}
public static void main(String[] args) {
int[] a = {3, 5, 1, 2, 6, 4, 7, 11, 23, 44, 3, 34, 8, 23, 6, 9};
getShellSort(a);
System.out.print("希爾排序:");
for(int i = 0; i < a.length; i++) {
System.out.print(a[i] + " " );
}
}
}
2.希爾排序的效能分析:
會根據增量的不同而不同,一般來說:
時間複雜度:
1. 最好情況:O(n^1.3)
2. 最壞情況:O(n^2)
空間複雜度:O(1)
穩定性:不穩定(相同元素的相對位置會改變)
3.適用場景
3.1:希爾排序是對直接插入排序的一種優化,可以用於大型的陣列,希爾排序比插入排序和選擇排序要快的多,並且陣列越大,優勢越大。