* @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
| 1151 | * @return `true` if the previous permutation was generated, `false` if the range was reset to the largest permutation. |
| 1152 | */ |
| 1153 | bool 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 | /** |