Test.c
#define _CRT_SECURE_NO_WARNINGS 1
#include "SelectSort.h"
void TestSelectSort()
{
int arr[] = { 9,1,2,5,7,4,8,6,3,5 };
int sz = sizeof(arr) / sizeof(arr[0]);
SelectSort(arr, sz);
PrintArray(arr, sz);
}
void TestHeapSort()
{
int arr[] = { 9,1,2,5,7,4,8,6,3,5 };
int sz = sizeof(arr) / sizeof(arr[0]);
HeapSort(arr, sz);
PrintArray(arr, sz);
}
int main()
{
TestHeapSort();
return 0;
}
SelectSort.h
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
void PrintArray(int* a, int n);
void SelectSort(int* a, int n);
void HeapSort(int* a, int n);
SelectSort.c
#define _CRT_SECURE_NO_WARNINGS 1
#include "SelectSort.h"
void PrintArray(int* a, int n)
{
assert(a);
for (int i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
printf("\n");
}
void Swap(int* a, int* b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
void SelectSort(int* a, int n)
{
assert(a);
int begin = 0, end = n - 1;
while (begin < end)
{
int mini = begin, maxi = begin;
for (int i = begin + 1; i <= end; i++)
{
if (a[i] < a[mini])
mini = i;
if (a[i] > a[maxi])
maxi = i;
}
Swap(&a[begin], &a[mini]);
if (begin == maxi)
{
maxi = mini;
}
Swap(&a[end], &a[maxi]);
begin++;
end--;
}
}
void AdjustDown(int* a, int size, int parent)
{
int child = parent * 2 + 1;
while (child < size)
{
if (child + 1 < size && a[child + 1] > a[child])
{
child++;
}
if (a[child] > a[parent])
{
Swap(&a[child], &a[parent]);
parent = child;
child = parent * 2 + 1;
}
else
{
break;
}
}
}
void HeapSort(int* a, int n)
{
for (int i = (n - 1 - 1) / 2; i >= 0; i--)
{
AdjustDown(a, n, i);
}
int end = n - 1;
while (end > 0)
{
Swap(&a[0], &a[end]);
AdjustDown(a, end, 0);
end--;
}
}