In the middle of qsort, is there a way to stop it?
-
qsort is an essential part of the standard C library in all platforms. In the compare function introduced to this function, I may conclude that two items are identical and I decide not to continue the process of sorting elements. How can I inform this to qsort not to continue sorting?
-
You can
longjmp
out of your comparison function.Also, just post your spam link and be done, thanks.
-
@SeppJ Oh no! It's dangerous. Thanks anyway.
What's spam link? I'm not a spammer!
-
For reference: https://stackoverflow.com/questions/79285431/in-the-middle-of-qsort-is-there-a-way-to-stop-it
-
Since this was posted to the C++ section of the forum, I suggest
std::sort
+ exceptions (the topic has been moved to C, so my answer is not really useful any more, but maybe still fun to play with)#include <algorithm> #include <fmt/core.h> #include <fmt/ranges.h> #include <vector> #include <stdexcept> using namespace std; bool compare(int a, int b) { fmt::println("{} <=> {}?", a, b); if (a == b) throw runtime_error("Equal numbers compared"); return a < b; } int main() { vector<int> a {1,5,3,5,6,2}; try { sort(a.begin(), a.end(), compare); } catch (const runtime_error &e) { fmt::println("Stopped sorting: {}!", e.what()); } fmt::print("A: {}!", a); }