您的位置:首页 > 其它

PAT1098 Insertion or Heap Sort

2015-11-26 15:15 393 查看

题目链接:

http://www.nowcoder.com/pat/5/problem/4322

题目大意:

判断插入排序还是堆排序。

首先判断下是哪种排序,是则以此排序方式再迭代一步。

代码:

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
using namespace std;
int dest[105];
int N;
int flag;
bool isEqual(int* sort)
{
for (int i = 0; i < N; i++)
{
if (sort[i] != dest[i])
{
return false;
}
}
return true;
}
void Insertion_Sort(int* sort,int N)
{
for (int i = 1; i < N; i++)
{
int tmp = sort[i];
int j;
for (j = i; j>0 && sort[j - 1] >= tmp; j--)
{
sort[j] = sort[j - 1];
}
sort[j] = tmp;
if (flag == 1)
{
return;
}
if (isEqual(sort))
{
flag = 1;
}
}

}
void PercDown(int* sort,int parent,int n)
{
int child;
int tmp = sort[parent];
for (; parent * 2+1 <= n-1; parent = child)
{
child = parent * 2+1;
if (child != n-1 && sort[child] < sort[child + 1])
{
child++;
}
if (tmp >= sort[child])
{
break;
}
else
{
sort[parent] = sort[child];
}
}
sort[parent] = tmp;
}
void swap(int* a,int* b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
void Heap_Sort(int* sort,int N)
{
for (int i = N / 2; i >= 0; i--) //调成最大堆
{
PercDown(sort,i,N);
}
for (int i = N - 1; i >= 0; i--)
{
swap(&sort[0],&sort[i]);
PercDown(sort,0,i);
if (flag == 2)
{
return;
}
if (isEqual(sort))
{
flag = 2;
}
}
}
int main()
{
int init[105];
int insertionSort[105];
int heapSort[105];

flag = 0;
scanf("%d",&N);
for (int i = 0; i < N; i++)
{
scanf("%d",&init[i]);
}
for (int i = 0; i < N; i++)
{
scanf("%d",&dest[i]);
}
for (int i = 0; i < N; i++)
{
insertionSort[i] = heapSort[i] = init[i];
}
Insertion_Sort(insertionSort,N);
Heap_Sort(heapSort,N);
if (flag == 1)
{
printf("Insertion Sort\n");
printf("%d", insertionSort[0]);
for (int i = 1; i < N; i++)
{
printf(" %d",insertionSort[i]);
}
}
else if (flag == 2)
{
printf("Heap Sort\n");
printf("%d", heapSort[0]);
for (int i = 1; i < N; i++)
{
printf(" %d", heapSort[i]);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息