Skip to content

Commit 5981ee0

Browse files
committed
just test to use quick sort to replace heapsort
1 parent b377902 commit 5981ee0

File tree

1 file changed

+17
-14
lines changed

1 file changed

+17
-14
lines changed

source/module_base/mymath.cpp

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
#include "mymath.h"
22

33
#include "timer.h"
4+
#include <algorithm> // For std::sort
5+
#include <vector>
6+
#include <utility> // For std::pair
47

58
namespace ModuleBase
69
{
@@ -36,32 +39,32 @@ void heapAjust(double *r, int *ind, int s, int m)
3639
void heapsort(const int n, double *r, int *ind)
3740
{
3841
ModuleBase::timer::tick("mymath", "heapsort");
39-
int i = 0, ic = 0;
40-
double rc = 0.0;
41-
4242
if (ind[0] == 0)
4343
{
44-
for (i = 0; i < n; i++)
44+
for (int i = 0; i < n; i++)
4545
{
4646
ind[i] = i;
4747
}
4848
}
4949

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)
5152
{
52-
heapAjust(r, ind, i, n - 1);
53+
pairs[i] = {r[i], ind[i]};
5354
}
5455

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)
5663
{
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;
6466
}
67+
6568
ModuleBase::timer::tick("mymath", "heapsort");
6669
return;
6770
}

0 commit comments

Comments
 (0)