#include <stdio.h>
#include <stdlib.h>
void HeapAdjust(int a[], int i, int n);/*此处从0开始存放*/
/*从小到大排用的大根堆,堆顶元素a[0]>a[1]。插入排序a[0]a[1]必定有序,a[0]<a[1]*/
int main()
{
int n,i=0,Isinsertion=1,Pos;
scanf("%d", &n);
int *data = (int*)malloc(sizeof(int)*n);
int *sorted = (int*)malloc(sizeof(int)*n);
while (i < n)
scanf("%d",&data[i++]);
i = 0;
while (i < n)
scanf("%d", &sorted[i++]);
/*判断是否插入排序*/
for (i = 0; i < n; i++)
if (sorted[i + 1] < sorted[i])
break;
Pos = i;
while (++i<n)
if (data[i] != sorted[i]) {
Isinsertion = 0;
break;
}
if (!Isinsertion) {
printf("Heap Sort\n");
int size = n - 1,HeapTop;
while (sorted[size] > sorted[0])
size--;
HeapTop = sorted[size];
sorted[size] = sorted[0];
sorted[0] = HeapTop;
/*对堆顶元素进行下滤*/
HeapAdjust(sorted, 0, size-1);
}else {
printf("Insertion Sort\n");
int X = sorted[Pos + 1];
i = Pos;
while (sorted[i] > X) {
sorted[i + 1] = sorted[i];
i--;
}
sorted[i + 1] = X;
}
for (i = 0; i < n-1; i++)
printf("%d ",sorted[i]);
printf("%d", sorted[n-1]);
return 0;
}
void HeapAdjust(int a[], int i, int n)/*调整a[0……n]成大根堆*/
{
int X = a[i];
int Parent = i, Child = 2 * Parent+1;
while (Child <= n) {/*当左孩子存在时*/
if ((Child < n) && (a[Child + 1] > a[Child]))
Child++;
if (a[Child] <= X)
break;
a[Parent] = a[Child];
Parent = Child; Child = 2 * Parent+1;
}
a[Parent] = X;
}
1098. Insertion or Heap Sort
最新推荐文章于 2022-08-15 13:49:51 发布