-
-
Save danlark1/af88d7b0937e5d31e27b336853b1c377 to your computer and use it in GitHub Desktop.
quadratic sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int quadratic(int size) { | |
int num_solid = 0; | |
// gas means "infinity" | |
int gas = size + 1; | |
int comparison_count = 0; | |
std::vector<int> indices(size); | |
std::vector<int> values(size); | |
// indices are 0, 1, ..., size | |
// values are all infinite | |
for (int i = 0; i < size; ++i) { | |
indices[i] = i; | |
values[i] = gas; | |
} | |
// Enforce uniform input distribution! | |
std::random_device rd; | |
std::mt19937 g(rd()); | |
std::shuffle(indices.begin(), indices.end(), g); | |
sort(indices.begin(), indices.end(), [&](int x, int y) { | |
comparison_count += 1; | |
// If both infinite, set left. | |
// Otherwise gas is always more | |
if (values[x] == gas && values[y] == gas) { | |
values[x] = num_solid++; | |
return true; | |
} else if (values[x] == gas) { | |
return false; | |
} else if (values[y] == gas) { | |
return true; | |
} else { | |
return values[x] < values[y]; | |
} | |
}); | |
return comparison_count; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment