Click here to Skip to main content
15,888,461 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I've come across an examination question with the algorithm below in pseudo code. The questions asks: "How many comparisons are made if n is equal 10?"

Algorithm sort
Declare A(1 to n)
n = length(A)
for i = 1 to n
    for j = 1 to n-1 inclusive do
        if A[i-1] > A[i] then
swap( A[i-1], A[i] )
        end if
    next j
next i


What I have tried:

Quote:
The marking scheme says it's 100 but I think this is wrong and think it's 90. What are people's opinions?
Posted
Updated 8-Nov-18 1:28am
Comments
CPallini 8-Nov-18 8:23am    
Are you aware that A[i-1] is an out-of-bounds access when i = 1 ?
Member 14048071 8-Nov-18 10:55am    
Would it be out of bounds? I think it would be 0? Therefore accessing the first element of the array.
CPallini 8-Nov-18 16:37pm    
The first element of the array is A[1], because of Declare A(1 to n).

You are right, it does 90 comparisons if n is 10.
(assuming 'inclusive' applies to both the loops).
 
Share this answer
 
Depends, you could get 72, 80, 81, or 90. But probably not 100.
Simple way to find out: try it!
C#
int n = 10;
int count = 0;
for (int i = 1; i < n; i++)
    for (int j = 1; j < n - 1; j++)
        count++;
Console.WriteLine(count);            // 72
count = 0;
for (int i = 1; i <= n; i++)
    for (int j = 1; j < n - 1; j++)
        count++;
Console.WriteLine(count);            // 80
count = 0;
for (int i = 1; i < n; i++)
    for (int j = 1; j <= n - 1; j++)
        count++;
Console.WriteLine(count);            // 81
count = 0;
for (int i = 1; i <= n; i++)
    for (int j = 1; j <= n - 1; j++)
        count++;
Console.WriteLine(count);            // 90
Myself? Given that one of your loops is specific about "inclusive" and the other isn't I'd go with 81 ...
 
Share this answer
 
Comments
Rob Philpott 8-Nov-18 8:33am    
Yeah, the inclusive bit is weird isn't it. One assumes it means the higher bound of the array, but it could refer to the lower of both. And starting at 1 sounds like the sort of thing a 'VB Person' would do. Oh dear.
OriginalGriff 8-Nov-18 8:47am    
I always think that loops start at an inclusive lower bound (or else, why specify "i = 1" or "j = 1"?)
But the inclusion of "inclusive" on one loop does sort of exclude the other ... badly designed. Could well be VB :laugh:
Member 14048071 8-Nov-18 9:11am    
I think that's what's throwing me. I think it was written by a VB programmer.
Member 14048071 8-Nov-18 10:58am    
Also this is meant to be a bubble sort and I think i and j are mixed up. With the inner loop you'd be checking the same values over and over.
OriginalGriff 8-Nov-18 11:03am    
It's all a bit crap, really ... :laugh:

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