希爾排序
先將整個待排序列分割成爲若干個子序列分別進行直接插入排序,待整個序列中的記錄“基本有序”時,再對整個記錄進行一次直接插入排序,其實希爾排序就是分組直接插入排序。
java代碼:
public class ShellSort {
public static void main(String[] args) {
int array[] = {2,10,4,5,1,8};
showArray(array);
System.out.println("\n排序後");
shellSort(array);
showArray(array);
}
private static void shellSort(int[] arr) {
int i,j,step;
int len = arr.length;
for(step = len/2;step>0;step/=2)
{
for(i = 0;i<step;i++)
{
for(j=i+step;j<len;j+=step)
{
if(arr[j]<arr[j-step])
{
int temp = arr[j];
int k = j - step;
while(k>=0 && arr[k]>temp)
{
arr[k+step] = arr[k];
k-=step;
}
arr[k+step] = temp;
}
}
}
}
}
private static void showArray(int[] a)
{
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
}
}
C代碼:
//希爾排序
#include<stdio.h>
void showArray(int a[],int len)
{
for(int i=0;i<len;i++)
{
printf("%d ",a[i]);
}
}
void shellSort(int arr[],int len)
{
int i,j,step;
for(step = len/2;step>0;step/=2)
{
for(i = 0;i<step;i++)
{
for(j=i+step;j<len;j+=step)
{
if(arr[j]<arr[j-step])
{
int temp = arr[j];
int k = j - step;
while(k>=0 && arr[k]>temp)
{
arr[k+step] = arr[k];
k-=step;
}
arr[k+step] = temp;
}
}
}
}
}
int main()
{
int array[] = {2,10,4,5,1,8};
int len = sizeof(array)/sizeof(int);
showArray(array,len);
printf("\n排序後\n");
shellSort(array,len);
showArray(array,len);
return 0;
}
希爾排序是不穩定的排序,希爾排序的執行時間依賴於增量序列,其平均時間複雜度爲O(n1.3)。
希爾排序最好時間複雜度O(n),最壞O(n^2)