#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define PARANT(x) (((x)-1) >> 1)
#define LCHILD(x) (((x) << 1) + 1)
#define RCHILD(x) (((x) + 1) << 1)
#define INHEAP(n, x) (((x) >= 0) && ((x) < (n)))
// inline bool INHEAP(int n, int x)
// {
// return (((x) >= 0) && ((x) < (n)));
// }
int N, tmp;
vector<int> initial, partial;
void insertion_sort()
{
vector<int> insert = initial;
bool flag = false;
int cur = 1, i = 0, tmp = 0;
while (cur < N)
{
tmp = insert[cur];
for (i = 0; i < cur; i++)
{
if (insert[i] >= insert[cur])
break;
}
for (int j = cur; j > i; j--)
{
insert[j] = insert[j - 1];
}
insert[i] = tmp;
if (flag == true)
break;
if (insert == partial)
flag = true;
cur++;
}
if (flag == true)
{
printf("Insertion Sort\n");
for (int i = 0; i < N; i++)
{
printf("%d", insert[i]);
if (i != N - 1)
printf(" ");
else
printf("\n");
}
exit(0);
}
}
void perlocate_down(vector<int> &heap, int x, int n)
{
while (INHEAP(n, LCHILD(x)))
{
if (INHEAP(n, RCHILD(x)))
{
if (heap[x] < heap[LCHILD(x)] && heap[LCHILD(x)] <= heap[RCHILD(x)])
{
swap(heap[x], heap[RCHILD(x)]);
x = RCHILD(x);
}
else if (heap[x] < heap[RCHILD(x)] && heap[RCHILD(x)] <= heap[LCHILD(x)])
{
swap(heap[x], heap[LCHILD(x)]);
x = LCHILD(x);
}
else if (heap[x] < heap[LCHILD(x)])
{
swap(heap[x], heap[LCHILD(x)]);
x = LCHILD(x);
}
else if (heap[x] < heap[RCHILD(x)])
{
swap(heap[x], heap[RCHILD(x)]);
x = RCHILD(x);
}
else
break;
}
else
{
if (heap[x] >= heap[LCHILD(x)])
break;
else
{
swap(heap[x], heap[LCHILD(x)]);
x = LCHILD(x);
}
}
}
}
void heap_sort()
{
vector<int> heap = initial;
bool flag = false;
for (int i = PARANT(N - 1); i >= 0; i--)
perlocate_down(heap, i, N);
for (int i = N - 1; i > 0; i--)
{
swap(heap[0], heap[i]);
perlocate_down(heap, 0, i);
if (flag == true)
break;
if (heap == partial)
flag = true;
}
if (flag == true)
{
printf("Heap Sort\n");
for (int i = 0; i < N; i++)
{
printf("%d", heap[i]);
if (i != N - 1)
printf(" ");
else
printf("\n");
}
exit(0);
}
}
int main()
{
scanf("%d", &N);
for (int i = 0; i < N; i++)
{
scanf("%d", &tmp);
initial.push_back(tmp);
}
for (int i = 0; i < N; i++)
{
scanf("%d", &tmp);
partial.push_back(tmp);
}
insertion_sort();
heap_sort();
return 0;
}
1098 Insertion or Heap Sort (25 分)
最新推荐文章于 2024-07-14 21:01:25 发布