实现步骤: 1>我们可以将第一个元素看作有序序列,将后面元素看作无序序列,从头到尾依次扫描未排序序列,给无序区的元素找到适当插入位置,将其位置后所有元素后移,然后流出空位进行插入。 可以配合图解来理解:
直接插入排序完成了,我们来看看这个排序最好和最坏的情况,最坏的情况莫过于逆序,而最好的情况就是有序的。 所以越接近有序效率越高,于是之后便有了希尔排序 2. 希尔排序 希尔排序呢,其实还是插入排序的思想,只是将插入排序分解成gap个子序列,所有距离为gap的元素放在同一个子序列中,在给每一个序列分别进行插入排序。然后缩小间隔gap,例如gap=gap/3+1,重复上面操作,当gap==1时就相当于分了一个序列,这时的序列已经基本有序,所以排序速度依然很快。
#define _CRT_SECURE_NO_WARNINGS 1#include<iostream>using namespace std;template<class T>struct Less //降序的仿函数{ bool operator()(const T& s, const T& l) { return s < l; }};template<class T> //升序的仿函数struct Greater{ bool operator()(const T&s, const T& l) { return s > l; }};template<class T = int, class Compare = Greater<T>>void ShellSort(T* arr,int size){ int gap = size; Compare com; while (gap > 1) { gap = gap / 3 + 1; int pos = 0; for (int i = pos + gap; i < size; ++i) { T tmp = arr[i]; pos = i - gap; while (pos >= 0 && com(arr[pos],tmp)) { arr[pos + gap] = arr[pos]; pos -= gap; } arr[pos + gap] = tmp; } }}void Shelltest(){ int arr[] = { 7, 8, 2, 5, 7, 9, 3, 1, 4, 6, 2, 0, 11, 5, 14 }; ShellSort<int>(arr, sizeof(arr) / sizeof(arr[0]));}新闻热点
疑难解答