插入排序是一种简单的插入排序法,其基本思想是:
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void ShellSort(int* a, int n); //希尔排序
void PrintArray(int* a, int n); //打印
#define _CRT_SECURE_NO_WARNINGS
#include "Sort.h"
void PrintArray(int* a, int n)
{
for (int i = 0; i < n; ++i)
{
printf("%d ", a[i]);
}
printf("\n");
}
void ShellSort(int* a, int n)
{
int gap = n;
while (gap >1)
{
gap = gap / 3 + 1; //+1是可以保证最后一次是1
for(int i = 0; i < n - gap; ++i)
{
int end = i;
int tmp = a[end + gap];
while (end >= 0)
{
if (a[end] > tmp)
{
a[end + gap] = a[end];
end -= gap;
}
else
{
break;
}
}
a[end + gap] = tmp;
}
}
}
#define _CRT_SECURE_NO_WARNINGS
#include "Sort.h"
void TestShellSort()
{
int a[] = { 6,1,5,4,8,9,3,2,7,0 };
PrintArray(a, sizeof(a) / sizeof(int));
ShellSort(a, sizeof(a) / sizeof(int));
PrintArray(a, sizeof(a) / sizeof(int));
}
int main()
{
TestShellSort();
return 0;
}