Answer the question
In order to leave comments, you need to log in
How to count the number of element comparisons and moves in the quicksort algorithm?
Implemented a quick sort algorithm. Tell me where you need to put the counters in order to calculate how many times the elements of the matrix were compared with each other and how many times they were moved?
void quick(int *temp, int i, int j)
{
int c, x,t=0;
m=i; k=j;
c=temp[(m+k) / 2];
do
{while (temp[m]<c) m++;
while (temp[k]>c) k--;
if (m<=k)
{if(m!=k)NazQuick++;
x=temp[m];
temp[m]=temp[k];
temp[k]=x;
m++;
k--;
}t++;
} while (m<k);
if (i<k) quick(temp, i, k);
if (m<j) quick(temp, m, j);
}
Answer the question
In order to leave comments, you need to log in
I can't think of anything smarter than saying "after every comparison and after every move"
Try to stop using single letter variables. Wanted to help, but too lazy to understand the code.
I do it like this
void quick(int *temp, int i, int j)
{
int c, x,t=0;
m=i; k=j;
c=temp[(m+k) / 2];
do
{SravQuick++;
while (temp[m]<c) m++;
while (temp[k]>c) k--;
if (m<=k)
{if(m!=k)NazQuick++;
x=temp[m];
temp[m]=temp[k];
temp[k]=x;
m++;
k--;
}t++;
} while (m<k);
if (i<k) quick(temp, i, k);
if (m<j) quick(temp, m, j);
}
This is considered analytically. Why counters? Get a book on algorithms. There in the first chapters it is written how and what to calculate.
Complexity/growth rate is calculated analytically. It is clear that in the general case for the comparison algorithm it cannot be faster than nlogn.
To calculate more correctly, you need to overload comparison assignment operators, etc. and embed a counter in them like this
Although @xandox was right - why?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question