Files
2026-03-22 17:41:18 +08:00

120 lines
2.5 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include<iostream>
#include<stdlib.h>
#include<math.h>
using namespace std;
int threshold;
/* 请在这里补充你的代码即你所实现的sort函数 */
#define swap(type, a, b) do {type tmp = a; a = b; b = tmp;} while(0)
int partition(int* arr, int l, int r) {
int pivot = arr[l];
int i = l + 1, j = r;
while (i <= j) {
while (i <= r && arr[i] <= pivot) i++;
while (arr[j] > pivot) j--;
if (i < j) {
swap(int, arr[i], arr[j]);
i++; j--;
}
}
swap(int, arr[l], arr[j]);
return j;
}
void sift_down(int* arr, int l, int len, int root) {
while (root * 2 <= len) {
int child = root * 2;
if (child + 1 <= len && arr[l + child] > arr[l + child - 1]) {
child++;
}
if (arr[l + child - 1] > arr[l + root - 1]) {
swap(int, arr[l + root - 1], arr[l + child - 1]);
root = child;
} else {
break;
}
}
}
void heap_sort(int* arr, int l, int r) {
int len = r - l + 1;
for (int i = len / 2; i >= 1; i--) {
sift_down(arr, l, len, i);
}
printf("Heap:");
for (int i = 0; i < len; i++) {
printf("%d ", arr[l + i]);
}
printf("\n");
for (int i = len; i > 1; i--) {
swap(int, arr[l], arr[l + i - 1]);
sift_down(arr, l, i - 1, 1);
}
}
void sort_bi(int* arr, int l, int r, int limit) {
if (l >= r) return;
if (r - l + 1 <= threshold) {
return;
}
if (limit == 0) {
heap_sort(arr, l, r);
return;
}
int p = partition(arr, l, r);
sort_bi(arr, l, p - 1, limit - 1);
sort_bi(arr, p + 1, r, limit - 1);
}
void insertion_sort(int* arr, int n) {
for (int i = 2; i <= n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 1 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
void sort(int *R, int n) {
int depth_limit = floor(2 * log2(n));
printf("depth_limit:%d\n", depth_limit);
sort_bi(R, 1, n, depth_limit);
printf("Intermediate:");
for (int i = 1; i <= n; i++) {
printf("%d ", R[i]);
}
printf("\n");
insertion_sort(R, n);
}
int main()
{
int n,i;
int a[50010];
scanf("%d %d", &n, &threshold);
for (i = 1; i <= n; i++)
scanf("%d", &a[i]);
sort(a,n);
printf("Final:");
for (i = 1; i <= n; i++)
printf("%d ",a[i]);
printf("\n");
return 0;
}