Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 31 additions & 21 deletions source/module_base/mymath.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
#include "mymath.h"

#include "timer.h"
#include <algorithm> // For std::sort
#include <vector>
#include <utility> // For std::pair

namespace ModuleBase
{
Expand All @@ -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];

Expand All @@ -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<std::pair<double, int>> 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<double, int>& a, const std::pair<double, int>& 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;
}
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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;
}
}
}

Expand All @@ -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;
Expand Down
Loading