希尔排序(ShellSort)

时间复杂度O(n^1.25)~O(1.6n^1.25)
空间复杂度:O(1)

#include<iostream>
using namespace std;


void ShellSort(int *arr, int size)
{
    int gap = size; //两个数之间的距离
    while (gap > 1)
    {
        gap = gap / 3 + 1;
        for (int i = gap; i < size; i++)  //和直接插入排序的思想相同
        {
            int end = i - gap;
            while (arr[end] > arr[end + gap] && end >= 0)
            {
                swap(arr[end], arr[end + gap]);
                end -= gap;
            }
        }
    }
}

void Print(int* arr, int size)
{
    for (int i = 0; i < size; i++)
    {
        cout << arr[i] << " ";
    }
    cout << endl;
}
int main()
{
    int arr[] = { 2, 5, 4, 9, 3, 6, 8, 7, 1, 0 };
    int size = sizeof(arr) / sizeof(arr[0]);
    Print(arr, size);
    ShellSort(arr, size);
    Print(arr, size);
    getchar();
    return 0;
}

你可能感兴趣的:(希尔排序)