July 04, 2024, 06:48:15 PM

News:

IonicWind Snippit Manager 2.xx Released!  Install it on a memory stick and take it with you!  With or without IWBasic!


Sort array by an element of the array

Started by RitchieF, January 01, 2012, 08:16:55 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

RitchieF

January 01, 2012, 08:16:55 AM Last Edit: January 01, 2012, 09:41:17 AM by RitchieF
Hi all,
is it possible to sort an array by an element of this array ?
I'd need to sort ad[] by ad[].dis

Thanks
Richard

QuoteTYPE Points
   def dis:double
   DEF ax:double
   DEF ay:double
ENDTYPE

int i,nnn
double dis1
DEF ad[10]:points
nnn=5

ad[1].ax = 60  : ad[1].ay = 120
ad[2].ax = 190 : ad[2].ay = 100
ad[3].ax = 220 : ad[3].ay = 440
ad[4].ax = 100 : ad[4].ay = 50
ad[5].ax = 400 : ad[5].ay = 350
   
OPENCONSOLE   

   FOR i = 1 to nnn
      ad.dis = dis(0, 0, ad.ax, ad.ay)
      PRINT " ",i," ->",ad.dis,ad.ax,ad.ay   
   NEXT i


PRINT:PRINT "Press any key to continue"
DO:UNTIL INKEY$ <> ""
CLOSECONSOLE
END

'Calculates the distance between x0/y0  and the x/y coordinate :  
SUB dis(d1 As Double, d2 As Double, d3 As Double, d4 As Double),Double
dis1 = ((d3 - d1) ^ 2 + (d4 - d2) ^ 2) ^ 0.5
RETURN dis1
ENDSUB

   

billhsln

Note:  DEF ad[10]:points means you have ad[0] - ad[9], all arrays are base 0, not base 1.

Fix your code:

  FOR i = 1 to nnn
      ad[i].dis = dis(0, 0, ad[i].ax, ad[i].ay)
      PRINT " ",i," ->",ad[i].dis,ad[i].ax,ad[i].ay   
   NEXT i


Add this sort, which the 2 commented lines are what you would use if you started at base 0, the ones below are what you would use since you are starting at 1.


'======================
Sub BubbleSort(max:INT)
'======================
DEF i, j:INT
DEF tdis:DOUBLE
DEF tax, tay:DOUBLE

'For i = Max to 1 Step -1
For i = Max to 2 Step -1
' For j = 0 to i - 1
For j = 1 to i - 1
' Compare neighboring elements
IF ad[j].dis <= ad[j+1].dis
tdis = ad[j].dis
tax = ad[j].ax
tay = ad[j].ay
ad[j].dis = ad[j+1].dis
ad[j].ax = ad[j+1].ax
ad[j].ay = ad[j+1].ay
ad[j+1].dis = tdis
ad[j+1].ax = tax
ad[j+1].ay = tay
End If
Next j
Next i
Return
ENDSUB
Endsub


Hope this is what you are looking for.  This is the simple Bubble Sort.

Bill
When all else fails, get a bigger hammer.

RitchieF

Thanks Bill,

works fine here though I'd need the other sorting direction.

Richard

billhsln

When all else fails, get a bigger hammer.