码迷,mamicode.com
首页 > 其他好文 > 详细

希尔排序

时间:2014-09-14 19:17:57      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   strong   for   

图示

   bubuko.com,布布扣

参考代码

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]);
        }
    }
}

测试

bubuko.com,布布扣
#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)

稳定性

不稳定

希尔排序

标签:style   blog   http   color   io   os   ar   strong   for   

原文地址:http://www.cnblogs.com/kaituorensheng/p/3971298.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!