0
$\begingroup$

What is the time complexity of the following procedure?

for $x \in \{1,\ldots,n\}$:
$\quad$ $i \gets \lfloor n/2 \rfloor$
$\quad$ while $i \neq x$:
$\quad\quad$ if $i > x$ then $i \gets i -1$, otherwise $i \gets i + 1$.

According to me, the time complexity is $O(n^2)$. The inner while loop starts at $n/2$ and moves towards the value of $x$, worst case it runs $n/2$ times, and best case it runs 0ドル$ times.

What is the exact time complexity of this procedure?

Yuval Filmus
281k27 gold badges317 silver badges515 bronze badges
asked Apr 10, 2021 at 6:18
$\endgroup$
4
  • $\begingroup$ cs.stackexchange.com/q/23593/755 $\endgroup$ Commented Apr 10, 2021 at 6:25
  • $\begingroup$ Yes, but I want to know if my intuition is correct? $\endgroup$ Commented Apr 10, 2021 at 6:28
  • $\begingroup$ I suggest following the systematic methodology there, then editing your question to show your work. That's how you can verify your intuition. $\endgroup$ Commented Apr 10, 2021 at 6:30
  • 2
    $\begingroup$ Please, post text as text, not as photographs of text. This is not a website for photographers who want to critique your use of color and perspective. It should be possible to copy&paste your text. It also makes your question unreadable to the blind and visually impaired. It also makes it impossible to index both by Stack Exchange's own search engine as well as Google, Bing, and co. $\endgroup$ Commented Apr 10, 2021 at 11:44

2 Answers 2

1
$\begingroup$

Assume $\frac{N}{2}\in\mathbb{N}$, $\frac{N}{2}+(\frac{N}{2}-1)+\cdots+1+0+1+\cdots +(\frac{N}{2}-1)=\frac{N}{2}+2\times\sum_{k=1}^{N/2-1}k=\frac{N}{2}+\frac{N^2-2N}{4}=\frac{N^2}{4}\in O(N^2)$

answered Apr 10, 2021 at 15:11
$\endgroup$
2
  • $\begingroup$ That equation cannot be true (although the sums is indeed in $O(N^2$). $\endgroup$ Commented Apr 10, 2021 at 15:58
  • $\begingroup$ @Steven I used - instead of + by mistake, I edited it and wrote it more precisely. Are there any other error here? $\endgroup$ Commented Apr 10, 2021 at 16:21
0
$\begingroup$

The while loop runs for $|x - \lfloor n/2 \rfloor|$ many iterations. Therefore the running time is proportional to $$ \sum_{x=1}^n |x - \lfloor n/2 \rfloor|. $$ To ease the calculation a bit, let us assume that $n$ is even. We break the sum into two parts: $$ \sum_{x=1}^{n/2} (n/2 - x) + \sum_{x=n/2+1}^n (x - n/2) = \sum_{x=0}^{n/2-1} x + \sum_{x=1}^{n/2} x = \frac{(n/2-1)(n/2)}{2} + \frac{(n/2)(n/2+1)}{2} = \Theta(n^2). $$

answered Apr 13, 2021 at 8:24
$\endgroup$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.