Answer the question
In order to leave comments, you need to log in
How to simulate the correct speed of various sorts with usleep?
I am writing a visualization of various sorts in c++ and SFML. I wish the sortings could be noticed at all. I would also like to see the difference and similarity in execution time between different sorts, i.e. insertion sort and selection sort should be done in about the same time on the same array. I artificially slow down sorts, here is an example:
void selection_sort (elem a[], int size)
{
int min = a[0].value, min_index;
for (int i = 0 ; i < size; i++)
{
min_index = i; usleep(90);
min = a[i].value; usleep(90);
for (int j = i; j < size; j++)
{
usleep(90);
if (a[j].value< min)
{
min = a[j].value; usleep(90);
min_index = j; usleep(90);
}
}
swap_elements(a, i, min_index); usleep(90);
}
}
Answer the question
In order to leave comments, you need to log in
You have stumbled upon an important property of asymptotic analysis. O(n^2) - means that for sufficiently large n, the running time will be approximately n^2 up to a constant. This same constant can be at least 0.5, at least 10000000.
Compare 2 algorithms:
// n(n-1)/2 инкремента.
for(i = 0; i < n; ++i){
for (j = i+1; j < n; j++) {
cnt1++;
}
}
// n^2 инкремента.
for(i = 0; i < n; ++i){
for (j =0; j < n; j++) {
cnt2++;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question