首页 > 代码库 > 希尔排序

希尔排序

图示

   

参考代码

void shellSort(int A[], int lens){    if (A == NULL || lens <=0)        return;    for (int gap = lens/2; gap >0; gap /= 2)    {        for (int i = gap; i < lens; i+=1)        {            for (int j = i-gap; j >= 0 && A[j] > A[j+gap]; j-=gap)                swap(A[j], A[j+gap]);        }    }}

测试

#include <iostream>using namespace std;void shellSort(int A[], int lens){    if (A == NULL || lens <=0)        return;    for (int gap = lens/2; gap >0; gap /= 2)    {        for (int i = gap; i < lens; i+=1)        {            for (int j = i-gap; j >= 0 && A[j] > A[j+gap]; j-=gap)                swap(A[j], A[j+gap]);        }    }}void tranverse(int A[], int lens){    for (int i = 0; i < lens; ++i)        cout << A[i] << " ";    cout << endl;}int main(){    int A[] = {5, 2, 9, 1, 3, 2, 2, 7};    int lens = sizeof(A) / sizeof(*A);    tranverse(A, lens);    shellSort(A, lens);    tranverse(A, lens);}
View Code

性能

空间复杂度:O(1)

时间复杂度好于O(n2)

稳定性

不稳定

希尔排序