【源代码】C++数据结构算法(十五)排序——希尔排序

日常说明:有错误欢迎大家指正。另外本博客所有的代码博主编写后均调试通过。重要提醒!!!!博主使用的是VS2017,如果有低版本的小伙伴最好新建空项目将此代码复制上去。
更多算法请关注我的算法专栏https://blog.csdn.net/column/details/20417.html
运行结果:这里写图片描述
ShellSort.h

#define LIST_INIT_SIZE 20;
#define LIST_CREMENT 10 ;
typedef int Datatype;
#include<iostream>
#include<exception>
using namespace std;


class List
{
public:
    List();
    ~List();
    /*void ListInsert(int i, Datatype e);*/
    void ListInsert(int n, int values[]);
    void shell_insert(List&, int increm);
    void shell_sort(List&);

//private:
    Datatype *elem;
    int length;
    int list_size;
};

ShellSort.cpp

#include "ShellSort.h"
#include"malloc.h"


List::List()
{
    this->list_size = LIST_INIT_SIZE;
    length = 0;
    this->elem = new Datatype[list_size];
    if ( !this->elem)
    {
        throw logic_error("分配空间失败");
    }
}
List::~List()
{
    delete[]this->elem;
}
void List::ListInsert(int n,int values[])
{

    if (this->length >= this->list_size)//扩容
    {
        this->length += LIST_CREMENT;
        this->elem = new Datatype(this->length);
    }
    for (int i = 1; i <= n; i++)//将数组中的元素一次赋值到顺序表
    {
        this->elem[i] = values[i];
        length++;
    }

}
void List::shell_insert(List&list,int increm)
{
    for (int i = increm+1; i <=list.length; ++i)
    {
        if (list.elem[i] < list.elem[i - increm])
        {
            list.elem[0] = list.elem[i];
            int j;
            for (j = i - increm; j >0&&(list.elem[0]<list.elem[j]); j-=increm)
            {
                list.elem[j + increm] = list.elem[j];
            }
            list.elem[j + increm] = list.elem[0];
        }   
    }
}
void List::shell_sort(List&list)
{
    int arr[3] = { 5,3,1 };
    for (int i = 0; i < 3; i++)
    {
        list.shell_insert(list, arr[i]);
    }
};


int main()
{
    int n;
    List list;
    cout << "需要输入的数据个数:";
    cin >> n;
    int *values;
    values= new Datatype(n);
    cout << endl;
    cout << "请输入"<<n<<"个数据元素:";
    for (int i = 1; i <=n; i++)
    {

        cin >> values[i];
    }
    list.ListInsert(n,values);
    list.shell_sort(list);
    cout << endl;
    cout << "希尔排序后list为:";
    for (int i = 1; i <= n; i++)
    {
        cout << list.elem[i]<<" ";
    }
    cout << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/handoking/article/details/80314883