<T>LAPACK 0.1.2
C++ Template Linear Algebra PACKage
Loading...
Searching...
No Matches
lasrt.hpp
Go to the documentation of this file.
1
5//
6// Copyright (c) 2021-2023, University of Colorado Denver. All rights reserved.
7//
8// This file is part of <T>LAPACK.
9// <T>LAPACK is free software: you can redistribute it and/or modify it under
10// the terms of the BSD 3-Clause license. See the accompanying LICENSE file.
11
39#ifndef TLAPACK_LASRT_HH
40#define TLAPACK_LASRT_HH
41
42#include <algorithm>
43#include <utility>
44#include <vector>
45
47
48namespace tlapack {
49
50template <class idx_t, class d_t>
51int lasrt(char id, idx_t n, d_t& d)
52{
53 const idx_t SELECT = 20;
54 int dir = -1;
55
56 if (id == 'd' || id == 'D')
57 dir = 0; // descending
58 else if (id == 'i' || id == 'I')
59 dir = 1; // ascending
60
61 if (dir == -1) return -1;
62 if (n < 0) return -2;
63 if (n <= 1) return 0;
64
65 std::vector<std::pair<idx_t, idx_t>> stack;
66 stack.emplace_back(0, n - 1);
67
68 while (!stack.empty()) {
69 auto [start, end] = stack.back();
70 stack.pop_back();
71
73 // Insertion sort
74 for (idx_t i = start + 1; i <= end; ++i) {
75 for (idx_t j = i; j > start; --j) {
76 if ((dir == 0 && d[j] > d[j - 1]) ||
77 (dir == 1 && d[j] < d[j - 1])) {
78 auto temp = d[j];
79 d[j] = d[j - 1];
80 d[j - 1] = temp;
81 }
82 else {
83 break;
84 }
85 }
86 }
87 }
88 else if (end - start > SELECT) {
89 // Median-of-three pivot
90 auto d1 = d[start];
91 auto d2 = d[end];
92 idx_t mid = (start + end) / 2;
93 auto d3 = d[mid];
94 auto pivot = d[start];
95
96 if (d1 < d2) {
97 if (d3 < d1)
98 pivot = d1;
99 else if (d3 < d2)
100 pivot = d3;
101 else
102 pivot = d2;
103 }
104 else {
105 if (d3 < d2)
106 pivot = d2;
107 else if (d3 < d1)
108 pivot = d3;
109 else
110 pivot = d1;
111 }
112
113 idx_t i = start;
114 idx_t j = end;
115 while (true) {
116 while (i <= end && ((dir == 0 && d[i] > pivot) ||
117 (dir == 1 && d[i] < pivot)))
118 ++i;
119 while (j >= start && ((dir == 0 && d[j] < pivot) ||
120 (dir == 1 && d[j] > pivot)))
121 --j;
122
123 if (i < j) {
124 auto temp = d[i];
125 d[i] = d[j];
126 d[j] = temp;
127 ++i;
128 --j;
129 }
130 else {
131 break;
132 }
133 }
134
135 if (j - start > end - j - 1) {
136 stack.emplace_back(start, j);
137 stack.emplace_back(j + 1, end);
138 }
139 else {
140 stack.emplace_back(j + 1, end);
141 stack.emplace_back(start, j);
142 }
143 }
144 }
145
146 return 0;
147}
148
149} // namespace tlapack
150
151#endif // TLAPACK_LASRT_HH
Sort the numbers in D in increasing order (if ID = 'I') or in decreasing order (if ID = 'D' ).
Definition arrayTraits.hpp:15
typename traits::real_type_traits< Types..., int >::type real_type
The common real type of the list of types.
Definition scalar_type_traits.hpp:113