diff --git a/source/module_base/mymath.cpp b/source/module_base/mymath.cpp index 7a04750db6..d5c5e1d22d 100644 --- a/source/module_base/mymath.cpp +++ b/source/module_base/mymath.cpp @@ -1,6 +1,9 @@ #include "mymath.h" #include "timer.h" +#include // For std::sort +#include +#include // For std::pair namespace ModuleBase { @@ -14,11 +17,13 @@ void heapAjust(double *r, int *ind, int s, int m) for (j = 2 * s; j <= m; j *= 2) { - if (j < m && (r[j] < r[j + 1])) + if (j < m && (r[j] < r[j + 1])) { j++; +} - if (!(rc < r[j])) + if (!(rc < r[j])) { break; +} r[s] = r[j]; @@ -36,32 +41,32 @@ void heapAjust(double *r, int *ind, int s, int m) void heapsort(const int n, double *r, int *ind) { ModuleBase::timer::tick("mymath", "heapsort"); - int i = 0, ic = 0; - double rc = 0.0; - if (ind[0] == 0) { - for (i = 0; i < n; i++) + for (int i = 0; i < n; i++) { ind[i] = i; } } - for (i = n / 2; i >= 0; i--) + std::vector> pairs(n); + for (int i = 0; i < n; ++i) { - heapAjust(r, ind, i, n - 1); + pairs[i] = {r[i], ind[i]}; } - for (i = n - 1; i > 0; i--) + // 使用 std::sort 对 pairs 按照 r 的值进行排序 + std::sort(pairs.begin(), pairs.end(), [](const std::pair& a, const std::pair& b) { + return a.first < b.first; + }); + + // 将排序结果写回 r 和 ind 数组 + for (int i = 0; i < n; ++i) { - rc = r[0]; - r[0] = r[i]; - r[i] = rc; - ic = ind[0]; - ind[0] = ind[i]; - ind[i] = ic; - heapAjust(r, ind, 0, i - 1); + r[i] = pairs[i].first; + ind[i] = pairs[i].second; } + ModuleBase::timer::tick("mymath", "heapsort"); return; } @@ -94,12 +99,14 @@ void hpsort(int n, double *ra, int *ind) if (ind[0] == 0) { - for (i = 1; i <= n; i++) + for (i = 1; i <= n; i++) { ind[i - 1] = i; +} } - if (n < 2) + if (n < 2) { return; // nothing to order +} k = n / 2; @@ -143,8 +150,9 @@ void hpsort(int n, double *ra, int *ind) } else if (ra[j] == ra[j + 1]) { - if (ind[j] < ind[j + 1]) + if (ind[j] < ind[j + 1]) { j = j + 1; +} } } @@ -164,11 +172,13 @@ void hpsort(int n, double *ra, int *ind) i = j; j = j + j + 1; } - else + else { j = ir + 1; // set j to terminate do-while loop +} } - else // this is the right place for rra + else { // this is the right place for rra j = ir + 1; // set j to terminate do-while loop +} } ra[i] = rra;