Sort and array: ascending or descending order

In this examples we will show how to order values in a array.

The only diference between arrays bellow is indicated in bold:

When comparing values, i will be always greater or equal to j.

Scripts will work both for numbers or string.
 


Sort: Ascending

<%
MyArray=Array(25,14,20,45,25,4,1,31,22,7)

max=ubound(MyArray)

For i=0 to max 
   For j=i 1 to max 
      if MyArray(i)>MyArray(j) then
          TemporalVariable=MyArray(i)
          MyArray(i)=MyArray(j)
          MyArray(j)=TemporalVariable
     end if
   next 
next 

Response.write ("The sorted values are those ones: <BR>") 

For i=0 to max 
  Response.write (MyArray(i) & "<BR>") 
next 
%>

The sorted values are these ones: 
1
4
7
14
20
22
25
25
31
45

Sort: Descending

<%
MyArray=Array("John","Peter","Anna","Alberto","George","Unai")

max=ubound(MyArray)

For i=0 to max 
   For j=i 1 to max 
      if MyArray(i)<MyArray(j) then
          TemporalVariable=MyArray(i)
          MyArray(i)=MyArray(j)
          MyArray(j)=TemporalVariable
     end if
   next 
next 

Response.write ("The sorted values are these ones: <BR>") 

For i=0 to max 
  Response.write (MyArray(i) & "<BR>") 
next 
%>

The sorted values are these ones: 
Unai
Peter
John
George
Anna
Alberto

 

AspTutorial.info.