What is the function ​alg1 ​doing ​from the following code snippet?

Updated on May 5, 2017 in [C] Beginner
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
6 on May 5, 2017

What is the function ​alg1 ​doing ​from the following code snippet? Provide the complexity analysis of the function.
To be done​ : documentation with the description of the algorithm and its complexity analysis.

 int​ alg1​(​int​[]​ a​,​ ​int​ b​)​ {
 int​ c ​=​ ​0;
 int​ d ​=​ a​.​length ​-​ ​1​;
 while​ ​(​d ​>=​ c​)​ {
 int​ e ​=​ alg2​(​a​,​ c​,​ d​,​ c​);
 if​ ​(​e ​==​ b​)​ {
 return​ a​[​e​];
 }​ ​else​ ​if​ ​(​e ​<​ b​)​ {
 c ​=​ e ​+​ ​1;
 }​ ​else​ { d ​=​ e ​-​ ​1;
 }
 }
 return​ ​-​1;
 }
 int​ alg2​(​int​[]​ a​,​ ​int​ b​,​ ​int​ c​,​ ​int​ d​)​ {
 int​ e ​=​ a​[​d​];
 int​ f ​=​ b;
 alg3​(​a​,​ d​,​ c​);
 for​ ​(​int​ i ​=​ b​;​ i ​<​ c​;​ i​++)​ {
 if​ ​(​a​[​i​] <​ e​)​ {
 alg3​(​a​,​ i​,​ f​);
 f​++;
 }
 }
 alg3​(​a​,​ c​,​ f​);
 return​ f;
 }
 void​ alg3​(​int​[]​ a​,​ ​int​ b​,​ ​int​ c​)​ {
 if​ ​(​b ​!=​ c​)​ {
 a[c] = (a[b] = (a[c] = a[b] ^ a[c]) ^ a[b]) ^ a[c];
 }
 }
 
  • Liked by
Reply
0 on May 5, 2017

alg1 () calculates which value in the array a is the wanted return value. For which it calls alg2 () which in turn calls alg3 ().
Without any context and comments in the code it unbelievably hard to figure out the reason behind doing this. Whoever wrote this code didn’t want anyone else to understand it 😛

  • Liked by
Reply
Cancel
4 on May 5, 2017

Thx, i have this question for that code:
What is the function ​alg1 ​doing ​from the following code snippet? Provide the complexity analysis of the function.
To be done​ : documentation with the description of the algorithm and its complexity analysis.

Helpful
on May 5, 2017

Oh boy. I would suggest starting at the end. Understand what alg3 does in alg2 and then understand what alg2 does and so on. And try running the code.

Helpful
on May 5, 2017

I might be a moron here but doesn’t alg1 just always return -1 meaning that it literally just turns whatever you do before ends up as -1.
Yes it does a ton of calculations but in the end they are all nullified because it only returns -1.

on May 5, 2017

i test the code and if a[1, 2, 3, 4, 5, 9, 10] and b is 5 alg1 will return 9 and if is bigger then  length – 1 will return -1

Helpful
on May 5, 2017

If what is bigger than length?

Show more replies
  • Liked by
Reply
Cancel