Update: Please file this under bad ideas. You don’t get anything for free in life and here is certainly proof. A simple idea gone bad. It is definitely something to learn from however.
Lazy programming challenge. If I pass a function that 50-50 returns true or false for the qsort’s comparision function I think that I can effectively unsort an array of structures writing 3 lines of code.
int main ( int argc, char **argv) { srand( time(NULL) ); /* 1 */ ... /* qsort(....) */ /* 2 */ }
…
int comp_nums(const int *num1, const int *num2) { float frand = (float) (rand()) / ((float) (RAND_MAX+1.0)); /* 3 */ if (frand >= 0.5f) return GREATER_THAN; return LESS_THAN; }
Any pitfalls I need to look for? Is it possible in fewer lines through swapping or is this the cleanest I get for 3 non trivial lines?
Bad idea. I mean really bad.
Your solution gives an unpredictable result, not a random result and there is a big difference. You have no real idea of what a qsort with a random comparison will do and whether all combinations are equally likely. This is the most important criterion for a shuffle: all combinations must be equally likely. Biased results equal big trouble. There’s no way to prove that in your example.
You should implement the Fisher-Yates shuffle (otherwise known as the Knuth shuffle).