#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=110;
int n;
int origin[maxn], temp[maxn], changed[maxn];
bool issame(int a[], int b[])
{
for (int i = 0; i < n; i++)
{
if (a[i] != b[i]) return false;
}
return true;
}
void show(int temp[])
{
for (int i = 1; i <= n; i++)
{
printf("%d", temp[i]);
if (i != n) printf(" ");
}
}
bool insert()
{
bool flag = false;
for (int i = 2; i <= n; i++)
{
if (i != 2 && issame(temp, changed)) flag = true;
sort(temp, temp + i + 1);
if (flag == true) return true;
}
return false;
}
void downadjust(int low, int high)
{
int i = low, j = i * 2;
while (j <= high)
{
if (j + 1 <= high && temp[j + 1] > temp[j]) j = j + 1;
if (temp[j] > temp[i])
{
swap(temp[j], temp[i]);
i = j;
j = 2 * i;
}
else break;
}
}
void heap()
{
bool flag = false;
for (int i = n / 2; i >= 1; i--)//建堆
{
downadjust(i, n);
}
for (int i = n; i >= 1; i--)
{
if (i != n && issame(temp, changed)) flag = true;
swap(temp[1], temp[i]);
downadjust(1, i - 1);
if (flag == true)
{
show(temp);
return;
}
}
}
int main()
{
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
scanf("%d", &origin[i]);
temp[i] = origin[i];
}
for (int i = 1; i <= n; i++)
{
scanf("%d", &changed[i]);
}
if (insert() == true)
{
printf("Insertion Sort\n");
show(temp);
}
else
{
printf("Heap Sort\n");
for (int i = 1; i <= n; i++)
{
temp[i] = origin[i];
}
heap();
}
return 0;
}
看网上叫柳婼大神的解法:(平均运行时间比前面多了2ms左右,但是省了很多行代码)
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
void downadjust(vector<int> &a,int low,int high)
{
int i = low;
int j = 2 * i;
while (j <= high)
{
if (j + 1 <= high && a[j + 1] > a[j]) j = j + 1;
if (a[j] > a[i])
{
swap(a[j], a[i]);
i = j;
j = 2 * i;
}
else break;
}
}
int main()
{
int n;
scanf("%d", &n);
vector<int> a(n+1), b(n+1);
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
for (int i = 1; i <= n; i++) scanf("%d", &b[i]);
int p = 2;
while (p<=n&&b[p - 1] <= b[p]) p++;
int index = p;
while (p<=n&&a[p] == b[p]) p++;
if (p == n + 1)
{
printf("Insertion Sort\n");
sort(b.begin() + 1, b.begin() + index + 1);
}
else
{
printf("Heap Sort\n");
p = n;
while (b[1] < b[p]) p--;
swap(b[1], b[p]);
downadjust(b,1, p-1);
}
printf("%d", b[1]);
for (int i = 2; i <= n; i++)
printf(" %d", b[i]);
return 0;
}