#include <cstdio>
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn = 1001;
int n,heap[maxn],t[maxn];;
bool isSame(int t[],int heap[])
{
for(int i = 1;i<=n;i++)
{
if(t[i] != heap[i])
return false;
}
return true;
}
void downAdjust(int low,int high)
{
int i = low,j = i*2;
while(j<=high)
{
if(j+1 <= high && heap[j] < heap[j+1])
j=j+1;
if(heap[j] > heap[i])
{
swap(heap[j],heap[i]);
i = j;
j = i*2;
}
else
break;
}
}
void creatHeap()
{
for(int i = n/2;i>0;i--)
{
downAdjust(i,n);
}
}
void printAarry(int a[])
{
for(int i = 1;i<=n;i++)
{
printf("%d",a[i]);
if(i!=n)
printf(" ");
}
}
void heapSort()
{
bool flag = false;
creatHeap();
for(int i = n;i>1;i--)
{
if(i!=n && isSame(heap,t) == true)
{
flag = true;
}
swap(heap[1],heap[i]);
downAdjust(1,i-1);
if(flag == true)
return;
}
}
bool inserSort()
{
bool flag = false;
int j;
for(int i = 2;i<n;i++)
{
if(i!=2 && isSame(heap,t) == true)
{
flag = true;
}
int temp = heap[i];
for(j = i;j>0 && heap[j-1] > temp;j--)
{
heap[j] = heap[j-1];
}
heap[j] = temp;
if(flag == true)
return true;
}
return false;
}
int main()
{
int s[maxn];
freopen("1.txt","r",stdin);
scanf("%d",&n);
for(int i = 1;i<=n;i++)
{
scanf("%d",&s[i]);
heap[i] = s[i];
}
for(int i = 1;i<=n;i++)
scanf("%d",&t[i]);
if(inserSort())
{
printf("Insertion Sort\n");
printAarry(heap);
}
else
{
for(int i = 1;i<=n;i++)
{
heap[i] = s[i];
}
heapSort();
printf("Heap Sort\n");
printAarry(heap);
}
return 0;
}
1098 Insertion or Heap Sort (25 分)(******)
猜你喜欢
转载自blog.csdn.net/qq_15556537/article/details/100854778
今日推荐
周排行