#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 105;
int init[maxn], first[maxn], inse[maxn], heap[maxn];
int N;
void print(int a[]) {
for (int i = 0; i < N - 1; i++) {
printf("%d ", a[i]);
}
printf("%d\n", a[N - 1]);
return;
}
bool test(int a[], int b[]) {
for (int i = 0; i < N; i++) {
if (a[i] != b[i]) return false;
}
return true;
}
bool insertsort() {
bool same = false;
for (int i = 1; i < N; i++) {
int temp = inse[i];
int j;
for (j = i; j > 0; j--) {
if(temp < inse[j - 1]) {
inse[j] = inse[j - 1];
}
else {
inse[j] = temp;
break;
}
}
if (j == 0) {
inse[0] = temp;
}
// print(inse); // only for test
if (same) {
printf("Insertion Sort\n");
print(inse);
return same;
}
same = test(first, inse);
}
return same;
}
void downAjust(int low, int high) {
int i = low, j = i * 2 + 1;
while (j <= high) {
if (j + 1 <= high && heap[j + 1] > heap[j]) {
j = j + 1;
}
if (heap[j] > heap[i]) {
swap(heap[i], heap[j]);
i = j;
j = i * 2 + 1;
} else {
break;
}
}
}
void bulidheap() {
for (int i = (N - 1) / 2; i >= 0; i--) {
downAjust(i, N);
}
}
bool heapsort() {
bool same = false;
bulidheap();
//print(heap); //test
for (int i = N - 1; i > 0; i--) { // order may be a problem
swap(heap[0], heap[i]);
downAjust(0, i - 1);
if (same) {
printf("Heap Sort\n");
print(heap);
return true;
}
same = test(heap, first);
//print(heap); // only for test.
}
return false;
}
int main() {
scanf("%d", &N);
int temp;
for (int i = 0; i < N; i++) {
scanf("%d", &temp);
inse[i] = heap[i] = init[i] = temp;
}
for (int i = 0; i < N; i++) {
scanf("%d", &first[i]);
}
if (!insertsort()) {
heapsort();
}
return 0;
}
1098 Insertion or Heap Sort (25分) PAT
猜你喜欢
转载自blog.csdn.net/Ike_Lin/article/details/104518580
今日推荐
周排行