#include <iostream>usingstd::cin;
usingstd::cout;
usingstd::endl;
void build_max_heap(int arr[], int curr, int size) {
if (curr >= size || 1 + curr * 2 >= size) { return; }
int root = curr;
int lchild = 1 + curr * 2;
int rchild = lchild + 1;
int maxNum = lchild;
if (rchild < size && arr[rchild] > arr[lchild]) { maxNum = rchild; }
if (arr[maxNum] > arr[root]) {
int t = arr[root];
arr[root] = arr[maxNum];
arr[maxNum] = t;
build_max_heap(arr, maxNum, size);
}
return;
}
void heap_sort(int a[], int n) {
build_max_heap(a, 0, n);
for (int i = (n / 2) - 1; i >= 0; i--) { build_max_heap(a, i, n); }
for (int i = n - 1; i >= 0; i--) {
int t = a[0]; a[0] = a[i]; a[i] = t;
build_max_heap(a, 0, i);
}
}
int main(void)
{
int* arr;
int n;
cin >> n;
arr = newint[n];
for (int i = 0; i < n; i++) { cin >> arr[i]; }
heap_sort(arr, n);
for (int i = 0; i < n; i++) { cout << arr[i] << " \n"[arr[i] == n]; }
return0;
}
单链表的冒泡
#include <iostream>
using std::cin;
using std::cout;
struct node {
node* next;
int val;
};
void bub_sort(node* root) {
node* now = root -> next;
while (now != nullptr) {
node* point = now -> next;
while (point > nullptr) {
if (now -> val > point -> val) {
int t = now -> val;
now -> val = point -> val;
point -> val = t;
}
point = point -> next;
}
now = now -> next;
}
return;
}
int main(void)
{
node* root = new node;
int n;
cin >> n;
node* now = root;
while (n--) {
node* tmp = new node;
tmp -> next = nullptr;
cin >> tmp -> val;
now -> next = tmp;
now = now -> next;
}
bub_sort(root);
now = root -> next;
while (now != nullptr) {
cout << now -> val << " \n"[now -> next == nullptr] ;
now = now -> next;
}
return 0;
}
无符号数的二进制倒序
#include <iostream>usingstd::cin;
usingstd::cout;
usingstd::endl;
unsignedint rev(unsignedint x) {
unsigned rt = 0;
for (int i = 0; i < 32; i++) {
rt = rt << 1;
rt += x % 2;
x = x >> 1;
}
return rt;
}
int main(void)
{
unsignedint x;
cin >> x;
cout << rev(x) << endl;
return0;
}
字符串匹配
#include <iostream>#include <cstring>usingstd::cin;
usingstd::cout;
usingstd::endl;
int match(char sa[], char sb[]) {
if (strlen(sa) == 0 && strlen(sb) == 0) { return0; }
if (strlen(sa) == 0 || strlen(sb) == 0) { return -1; }
if (sb[0] == '?') { return match(sa + 1, sb + 1); }
if (sb[0] == '*') {
for (int i = 0; i <= strlen(sa); i++) {
if (0 == match(sa + i, sb + 1)) { return0; }
}
return -1;
}
if (sb[0] == sa[0]) { return match(sa + 1, sb + 1); }
return -1;
}
int main(void)
{
char str0[256], str1[256];
cin >> str0 >> str1;
cout << match(str0, str1) << endl;
return0;
}