1.插入排序
void InsirtSort(int* a, int n)
{
printf("插入排序:\n");
for (int i = 1; i < n; i++)
{
int end = i - 1;
int tmp = a[i];
while (end >= 0)
{
if (a[end] > tmp)
{
a[end + 1] = a[end];
--end;
}
else
{
break;
}
}
a[end + 1] = tmp;
}
}
2.希尔排序
void ShellSort(int* a, int n)
{
printf("希尔排序\n");
int gap = n;
while (gap > 0)
{
gap /= 2;
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;
}
}
}
3. 冒泡排序
void BubbleSort(int* a, int n)
{
printf("冒泡排序\n");
for (int j = 0; j < n - 1; j++)
{
for (int i = 0; i < n - j - 1; i++)
{
if (a[i] > a[i + 1])
{
int tmp = a[i + 1];
a[i + 1] = a[i];
a[i] = tmp;
}
}
}
}
4. 选择排序
void Swap(int* p1, int* p2)
{
int tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
void SelectSort(int* a, int n)
{
printf("选择排序\n");
int begin = 0, end = n - 1;
while (begin < end)
{
int maxi = begin, mini = begin;
for (int i = begin; i <= end; i++)
{
if (a[i] > a[maxi])
{
maxi = i;
}
if (a[i] < a[mini])
{
mini = i;
}
}
Swap(&a[begin], &a[mini]);
Swap(&a[end], &a[maxi]);
begin++;
end--;
}
}
5. 堆排序
void Swap(int* p1, int* p2)
{
int tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
void AdjustDown(int* a, int n, int root)
{
int parent = root;
int child = parent * 2 + 1;
while (child < n)
{
if (child + 1 < n && a[child + 1] > a[child])
{
child += 1;
}
if (a[child] > a[parent])
{
Swap(&a[child], &a[parent]);
parent = child;
child = parent * 2 + 1;
}
else
{
break;
}
}
}
void HeapSort(int* a, int n)
{
printf("堆排序\n");
int i = 0;
for (i = n / 2 - 1; i >= 0; i--)
{
AdjustDown(a, n, i);
}
int end = n - 1;
for (i = 0; i < n; i++)
{
Swap(&a[0], &a[end--]);
AdjustDown(a, end, 0);
}
}