# Program Analysis

• 11-13-2001
Unregistered
Program Analysis
I'm having to do a bit of program analysis for one of my programs that is due for class tommorrow, and I'm a bit stuck on a very simple part for some people.

Ok I have to analyze three sections of my program. The function bubble sort, linear search, and binary search. Lets just focus on bubble sort since I should be able to apply the same concepts to the rest of the functions. Here's a snipit of code from the bubble sort function.

Bubble Sort:
void sortArray(int a[], int size)
{
int tmp;
for (int i = 0; i < size - 1; i = i + 1)
{
for (int j = 0; j < size - 1; j = j + 1)
if (a[j + 1] < a[j])
{
tmp = a[j];
a[j] = a[j + 1];
a[j + 1] = tmp;
}
}
}

I'm not real sure, but I think either the inner for loop or the if (a[j + 1] < a[j]) gets called the most. In which case I want to keep a count of how many times the one that's called the most gets executed. The only problem is I'm not real sure how to keep a count of how many times it's exectued. Can anyone enlighten me?
• 11-13-2001
zen
You could use a variable(s) that is incremented everytime part of your code is executed.
• 11-13-2001
Stoned_Coder
Dear oh dear..... for loops are COUNTED loops. You can work this out in your head. For every time the outer loop iterates the inner loop iterates size-1 times.
• 11-13-2001
Unregistered
Quote:

Originally posted by zen
You could use a variable(s) that is incremented everytime part of your code is executed.
Ok, Lets say I want to increament the variable everytime if(a[j + 1] < a[j]) statement is executed. How would I do that in code. That's my real problem.

Ok Stonded_Coder,

So basically I need to add a piece of code to my statement as such:

for (int i = 0; i < size -1; i = i + 1)
{
countBS = countBS + j;
for (int j = 0; j < size - 1; j = j + 1)
{
blah blah
}

since j is going to end of being size - 1. Correct?
btw: countBS stands for count_Bubble_Sort
I'm not sure, but I might need to declare j outside of the inner loop in order to do that.