What does this FORTRAN sorting subroutine do?

  • Context: Undergrad 
  • Thread starter Thread starter vsolute
  • Start date Start date
  • Tags Tags
    Function Program
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
1 reply · 2K views
vsolute
Messages
1
Reaction score
0
SUBROUTINE STIKA (X,N)
DIMENSION X(N)
IF (N. LT. 2) RETURN
DO 20 I=2, N
DO 10 J=1, I
IF(X(I) .GE. X(J)) GOTO 10


SAVE = X(I)
X(I) = X(J)
X(J) = SAVE
10 CONTINUE
20 CONTINUE
RETURN

If any have a good idea about the program please help

What i actually want is that, I want to know what this program routine will perform and i also want to translate into a high level language like vb or java


thanks
 
Mathematics news on Phys.org
The fragment
"Save= X(i)
X(i)= X(j)
X(j)= Save"

is a standard method of "swapping" two values. If X(i)= a and X(j)= b, then after "Save= X(i)", Save= a. After "X(i)= X(j)", X(i)= b. After "X(j)= Save", X(j)= a so we have swapped a and b. If you just said "X(i)= X(j), X(j)= X(i)" you would wind up with X(i) and X(j) having the same value, whatever was originally in X(j), because in that first "X(i)= X(j)" you lose the value of X(i). That's why you want to "save" it first.

In any case for any bit of code, like this, the simplest thing to do is to "walk through it". That is, go through it by hand seeing what happens. First, notice that if n= 1, the program does nothing because of "If n LT 2 Return". Supose n= 2, X(1)= a, X(2)= b.
The first time through the outer loop I= 2 so the inner loop becomes "For J= 1 to 2".
We start with J= 1. If X(I)= X(J), that is if X(2)= X(1), or a= b, nothing is done. If that is not true then we swap the two- X(1)= b, X(2)= a (you see why it might be sensible to jump over this if a= b).
Now we have J= 2. I= 2 also so X(I)=X(J) and we skip over the swap.
Since I was going "from 2 to 2", we are done- we now have X(1)= b, X(2)= a. We have swapped the two values.

Okay, let's try n= 3, X(1)= a, X(2)= b, X(3)= c.
We start with I= 2, J= 1, and swap X(1) and X(2): X(1)= b, X(2)= a.
Now, J becomes 2, X(I)= X(2)= X(J) so nothing is done

I becomes 3. J= 1 again, and we swap X(1) and X(3): X(1)= c, X(3)= b.
J= 2, so we swap X(2) and X(3): X(2)= b, X(3)= a.
J= 3, so X(I)= X(3)= X(J) and nothing is done.

Since we have done I from 2 to n= 3, we are done.

We started with X(1)= a, X(2)= b, and X(3)= c.
We ended with X(1)= c, X(2)= b, and X(3)= a.

Get the idea?

If not, try "walking through" the code with n= 4 and n= 5.