Click here to Skip to main content
15,891,943 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Counting each operation as 1 operation (including []), what is the number of times the while loop is executed in this code?

C++
int i, float x;
for(int j=1; j<n; j++)
{
 x=v[j];
 i=j-1;
  while(v[i] > x && i>=0) /** in context with this while loop **/ 
  {
     v[i+1]= v[i];
     i= i-1;
  }
  v[i+1]= x;
}


What I have tried:

counted the number of while loop operations for each iteration of the for loop. Wanted to re-check.
Posted
Updated 12-Jul-19 9:53am
v4
Comments
Maciej Los 30-Jun-19 10:19am    
What's the problem to check it out by the code?

That's a variation of bubble sort: so look up the Big O notation for that and you should be able to work it out.
Bubble Sort | Brilliant Math & Science Wiki[^]
 
Share this answer
 
Two nested loops each with max iterations n.
The total time complexity = n x n = n^2
 
Share this answer
 
It look like an inefficient way to reverse a list.
The while loop should run about (n²-n)/2 times.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900