|
1 | 1 | #include "mymath.h" |
2 | 2 |
|
3 | 3 | #include "timer.h" |
| 4 | +#include <algorithm> // For std::sort |
| 5 | +#include <vector> |
| 6 | +#include <utility> // For std::pair |
4 | 7 |
|
5 | 8 | namespace ModuleBase |
6 | 9 | { |
@@ -36,32 +39,32 @@ void heapAjust(double *r, int *ind, int s, int m) |
36 | 39 | void heapsort(const int n, double *r, int *ind) |
37 | 40 | { |
38 | 41 | ModuleBase::timer::tick("mymath", "heapsort"); |
39 | | - int i = 0, ic = 0; |
40 | | - double rc = 0.0; |
41 | | - |
42 | 42 | if (ind[0] == 0) |
43 | 43 | { |
44 | | - for (i = 0; i < n; i++) |
| 44 | + for (int i = 0; i < n; i++) |
45 | 45 | { |
46 | 46 | ind[i] = i; |
47 | 47 | } |
48 | 48 | } |
49 | 49 |
|
50 | | - for (i = n / 2; i >= 0; i--) |
| 50 | + std::vector<std::pair<double, int>> pairs(n); |
| 51 | + for (int i = 0; i < n; ++i) |
51 | 52 | { |
52 | | - heapAjust(r, ind, i, n - 1); |
| 53 | + pairs[i] = {r[i], ind[i]}; |
53 | 54 | } |
54 | 55 |
|
55 | | - for (i = n - 1; i > 0; i--) |
| 56 | + // 使用 std::sort 对 pairs 按照 r 的值进行排序 |
| 57 | + std::sort(pairs.begin(), pairs.end(), [](const std::pair<double, int>& a, const std::pair<double, int>& b) { |
| 58 | + return a.first < b.first; |
| 59 | + }); |
| 60 | + |
| 61 | + // 将排序结果写回 r 和 ind 数组 |
| 62 | + for (int i = 0; i < n; ++i) |
56 | 63 | { |
57 | | - rc = r[0]; |
58 | | - r[0] = r[i]; |
59 | | - r[i] = rc; |
60 | | - ic = ind[0]; |
61 | | - ind[0] = ind[i]; |
62 | | - ind[i] = ic; |
63 | | - heapAjust(r, ind, 0, i - 1); |
| 64 | + r[i] = pairs[i].first; |
| 65 | + ind[i] = pairs[i].second; |
64 | 66 | } |
| 67 | + |
65 | 68 | ModuleBase::timer::tick("mymath", "heapsort"); |
66 | 69 | return; |
67 | 70 | } |
|
0 commit comments