希尔排序是在插入排序的基础上改进得来。因为插入排序对于基本有序和小序列有较快的速度。但是对于大序列和无序的序列就有缺陷。因此希尔排序的思想就是将序列转化为若干小序列,每个小序列使用插入排序,最终实现基本有序,最后微调即可进一步优化排序方法。将前面所讲的排序时间复杂度从O(n2)降到O(n1.3),代码如下:
Input number (q to quite): 9 5 6 1 3 4 6 5 9 7 1 3 6 4 9 q
Your input List is: 9 5 6 1 3 4 6 5 9 7 1 3 6 4 9
After sort: 1 1 3 3 4 4 5 5 6 6 6 7 9 9 9
#include<iostream>
using namespace std;
#define MAXSIZE 100
struct List
{
int data[MAXSIZE];
int size;
};
void swap(List &L, int i, int j)
{
int temp = L.data[i];
L.data[i] = L.data[j];
L.data[j] = temp;
}
void show(const List &L)
{
for (int i = 0; i < L.size; i++)
cout << L.data[i] << " ";
cout << endl;
}
void ShellSort(List &L)
{
for (int increment = L.size / 2; increment > 0; increment /= 2) {
for (int i = increment; i < L.size; i++) {
if (L.data[i] < L.data[i - increment]) {
int temp = L.data[i],j;
for (j = i - increment; j >= 0 && temp < L.data[j]; j -= increment)
L.data[j + increment] = L.data[j];
L.data[j + increment] = temp;
}
}
}
}
void main()
{
List test;
cout << "Input number (q to quite): ";
int temp;
test.size = 0;
while (test.size <= MAXSIZE&&cin >> temp) {
test.data[test.size] = temp;
test.size += 1;
//cout << "Input number (q to quite): ";
}
cin.clear();
cin.ignore(100, '\n');
cout << "Your input List is: ";
show(test);
cout << "After sort: ";
ShellSort(test);
show(test);
}