十大排序-希尔排序

希尔排序
空间复杂度为O(1)
时间复杂度为最坏情况为O(\(n^{2}\)),最好情况是O(\(n^{1.3}\)),平均为O(nlogn)
是不稳定的

#include<iostream>
using namespace std;
#include<vector>

typedef int ElemType;

void ShellSort(ElemType a[],int n)
{
    int gap = n / 2;
    while(gap)
    {
        for(int i = gap ; i < n; i += gap)
        {
            int t = a[i],j;
            for(j = i - gap ; j >= 0 ;j -= gap)
            {
                if(a[j] > t)
                {
                    a[j + gap] = a[j];
                }
                else
                {
                    break;
                }
            }
            a[j+gap] = t; 
        }
        gap /= 2;
    }
}

void ShellSort2(vector<int> &a)
{
    int gap = a.size()/2;
    while(gap)
    {
        for(int i = gap ; i < a.size(); i += gap)
        {
            int t = a[i],j;
            for(j = i - gap ; j >= 0 ;j -= gap)
            {
                if(a[j] > t)
                {
                    a[j + gap] = a[j];
                }
                else
                {
                    break;
                }
            }
            a[j+gap] = t; 
        }
        gap /= 2;
    }
}

void ShellSort_lts(ElemType a[],int n)
{
    int gap = n / 2;
    while(gap)
    {
        for(int i = gap ; i < n; i += gap)
        {
            int t = a[i],j;
            for(j = i - gap ; j >= 0 ;j -= gap)
            {
                if(a[j] < t)
                {
                    a[j + gap] = a[j];
                }
                else
                {
                    break;
                }
            }
            a[j+gap] = t; 
        }
        gap /= 2;
    }
}

void ShellSort2_lts(vector<int> &a)
{
    int gap = a.size()/2;
    while(gap)
    {
        for(int i = gap ; i < a.size(); i += gap)
        {
            int t = a[i],j;
            for(j = i - gap ; j >= 0 ;j -= gap)
            {
                if(a[j] < t)
                {
                    a[j + gap] = a[j];
                }
                else
                {
                    break;
                }
            }
            a[j+gap] = t; 
        }
        gap /= 2;
    }
}


int main()
{
    int a[]={8,6,4,9,7,1,2,5,0};
    int n = sizeof(a) / sizeof(a[0]);
    vector<int> arr;
    for(int i = 0 ; i < n ; i++)
    {
        arr.push_back(a[i]);
    }

    ShellSort(a,n);
    for(int i=0;i<n;i++){
        cout<<a[i]<<" ";
    }
    cout<<endl;

    for(auto i : arr)
    {
        cout<<i<<" ";
    }
    cout<<endl;
    ShellSort2(arr);
    for(auto i : arr)
    {
        cout<<i<<" ";
    }
    cout<<endl;

    ShellSort_lts(a,n);
    for(int i=0;i<n;i++){
        cout<<a[i]<<" ";
    }
    cout<<endl;

    ShellSort2_lts(arr);
    for(auto i : arr)
    {
        cout<<i<<" ";
    }
    cout<<endl;

    system("pause");
    return  0;
}
``
posted @ 2020-07-09 19:56  Akmf's_blog  阅读(104)  评论(0)    收藏  举报