P
P
parkito2014-03-05 23:22:56
C++ / C#
parkito, 2014-03-05 23:22:56

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

5 answer(s)
N
Nikita Kolosov, 2014-03-05
@Anexroid

I can't think of anything smarter than saying "after every comparison and after every move"

D
Dmitry Guketlev, 2014-03-06
@Yavanosta

Try to stop using single letter variables. Wanted to help, but too lazy to understand the code.

P
parkito, 2014-03-05
@parkito

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);
}

However, it is considered incorrect.

X
xandox, 2014-03-07
@xandox

This is considered analytically. Why counters? Get a book on algorithms. There in the first chapters it is written how and what to calculate.

X
xseven, 2014-04-08
@xseven

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 question

Ask a Question

731 491 924 answers to any question