MCPcopy Create free account
hub / github.com/KaisenAmin/c_std / algorithm_prev_permutation

Function algorithm_prev_permutation

algorithm/algorithm.c:1153–1188  ·  view source on GitHub ↗

* @brief Generates the previous lexicographical permutation of a range. * * This function rearranges the elements in the range `[first, last)` into the previous lexicographical * permutation, as determined by the comparison function `comp`. If such a permutation is not possible, * the range is rearranged into the largest lexicographical order (sorted in descending order). * * @param first Po

Source from the content-addressed store, hash-verified

1151 * @return `true` if the previous permutation was generated, `false` if the range was reset to the largest permutation.
1152 */
1153bool algorithm_prev_permutation(void *first, void *last, size_t size, CompareFuncBool comp) {
1154 ALGORITHM_LOG("[algorithm_prev_permutation] Info: Generating previous permutation.");
1155 if (first == last) {
1156 ALGORITHM_LOG("[algorithm_prev_permutation] Warning: Empty range, returning false.");
1157 return false;
1158 }
1159
1160 char *i = (char *)last - size;
1161 while (i != (char *)first) {
1162 char *j = i;
1163 i -= size;
1164
1165 if (comp(j, i)) {
1166 char *k = (char *)last - size;
1167
1168 while (!comp(k, i)) {
1169 k -= size;
1170 }
1171
1172 ALGORITHM_LOG("[algorithm_prev_permutation] Info: Swapping elements.");
1173 swap(i, k, size);
1174 reverse(j, last, size);
1175
1176 ALGORITHM_LOG("[algorithm_prev_permutation] Success: Previous permutation generated.");
1177 return true;
1178 }
1179 if (i == (char *)first) {
1180 ALGORITHM_LOG("[algorithm_prev_permutation] Info: Resetting to largest permutation.");
1181
1182 reverse(first, last, size);
1183 return false;
1184 }
1185 }
1186
1187 return false;
1188}
1189
1190
1191/**

Callers

nothing calls this directly

Calls 2

swapFunction · 0.85
reverseFunction · 0.85

Tested by

no test coverage detected