按通常的插入排序和堆排序。每排序一步,就比较一次。
对于宏,最好不要使用自增、自减运算,否则可能产生意想不到的错误。
#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <cstdlib>
#define swap(a, b) {int tmp; tmp = a; a = b; b = tmp;}
bool heapSort(int arr[], int n, int target[]);
void heaplify(int arr[], int n);
bool insertionSort(int arr[], int n, int target[]);
bool compare(int arr[], int n, int target[]);
void perculatedown(int arr[], int n, int i);
int main(void) {
int arr1[200], arr2[200], target[200], n, i;
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d", arr1 + i);
arr2[i] = arr1[i];
}
for (i = 0; i < n; i++) {
scanf("%d", target + i);
}
if (heapSort(arr1, n, target)) {
puts("Heap Sort");
for (i = 0; i < n - 1; i++) {
printf("%d ", arr1[i]);
}
printf("%d\n", arr1[i]);
}
else {
insertionSort(arr2, n, target);
puts("Insertion Sort");
for (i = 0; i < n - 1; i++) {
printf("%d ", arr2[i]);
}
printf("%d\n", arr2[i]);
}
return 0;
}
bool insertionSort(int arr[], int n, int target[])
{
int i, j, tmp;
bool flag1 = true, flag2 = true;
for (i = 1; i < n && flag2; i++) {
tmp = arr[i];
for (j = i - 1; j >= 0; j--) {
if (arr[j] > tmp) {
arr[j + 1] = arr[j];
}
else {
break;
}
}
arr[j + 1] = tmp;
flag2 = flag1;
if (compare(arr, n, target)) {
flag1 = false;
}
}
return !flag2;
}
void heaplify(int arr[], int n)
{
int i = (n - 2) / 2;
while (i >= 0) {
perculatedown(arr, n, i);
i--;
}
return;
}
bool heapSort(int arr[], int n, int target[])
{
bool flag1 = true, flag2 = true;
int heapSize = n;
heaplify(arr, heapSize);
while (heapSize > 1 && flag2) {
heapSize--;
swap(arr[0], arr[heapSize]);
perculatedown(arr, heapSize, 0);
flag2 = flag1;
if (compare(arr, n, target)) {
flag1 = false;
}
}
return !flag2;
}
bool compare(int arr[], int n, int target[])
{
int i;
bool flag = true;
for (i = 0; i < n; i++) {
if (arr[i] != target[i]) {
flag = false;
break;
}
}
return flag;
}
void perculatedown(int arr[], int n, int i)
{
int largerIndex;
while (i * 2 + 1 < n) {
if (i * 2 + 2 < n) {
largerIndex = arr[i * 2 + 1] > arr[i * 2 + 2] ? i * 2 + 1 : i * 2 + 2;
largerIndex = arr[i] > arr[largerIndex] ? i : largerIndex;
}
else {
largerIndex = arr[i * 2 + 1] > arr[i] ? i * 2 + 1 : i;
}
if (largerIndex == i) {
break;
}
else {
swap(arr[i], arr[largerIndex]);
i = largerIndex;
}
}
return;
}