C++
有几个坑,写在插入排序那了(看了老久- -!)
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;
const int N = 110;
int A[N], B[N];
int a[N];
int n;
bool judge(int x[], int y[]) {
for (int i = 1; i <= n; ++i)
if (x[i] != y[i]) return false;
return true;
}
bool insert_sort(){
for(int i = 2; i <= n; ++i){
int j = i;
while(j > 1 && a[j] < a[j - 1]) swap(a[j], a[j - 1]), j--;
if(judge(a, B)){
//acwing:j可以赋值为i,pat:不能赋值为i
//很好理解,第i次迭代后,第i+1次迭代的下标显然是i+1
//堆排用sz维护待排序的数量,问题无意识地解决了,因为每次都有sz--
int j = i + 1;
while(j > 1 && a[j] < a[j - 1]) swap(a[j], a[j - 1]), j--;
return true;
}
}
return false;
}
void sink(int x, int sz) {
int t = x;
if (x * 2 <= sz && a[x * 2] > a[t]) t = x * 2;
if (x * 2 + 1 <= sz && a[x * 2 + 1] > a[t]) t = x * 2 + 1;
if (x != t) {
swap(a[x], a[t]);
sink(t, sz);
}
}
int cnt = 0;
bool heap_sort() {
for (int i = n / 2; i; --i) sink(i, n);
// for (int i = 1; i <= n; ++i) printf("%d ", a[i]);
// cout << endl;
int sz = n;
while (sz) {
if (judge(a, B)) {
swap(a[1], a[sz]);
sz--;
sink(1, sz);
return true;
}
swap(a[1], a[sz]);
sz--;
sink(1, sz);
}
return false;
}
int main() {
cin >> n;
for (int i = 1; i <= n; ++i) cin >> A[i];
for (int i = 1; i <= n; ++i) cin >> B[i];
for(int i = 1; i <= n; ++i) a[i] = A[i];
if (heap_sort()) {
printf("Heap Sort\n");
} else {
printf("Insertion Sort\n");
for(int i = 1; i <= n; ++i) a[i] = A[i];
insert_sort();
}
for (int i = 1; i <= n; ++i){
if(i - 1) printf(" ");
printf("%d", a[i]);
}
cout << endl;
return 0;
}