Multiple Array Sort

Share your advanced PureBasic knowledge/code with the community.
User avatar
geoff
Enthusiast
Enthusiast
Posts: 128
Joined: Sun Apr 27, 2003 12:01 am
Location: Cornwall UK
Contact:

Multiple Array Sort

Post by geoff »

The PureBasic command SortArray() is fast and convenient but you
often need to put several arrays into consistent order.

For example, if you have the arrays word$() and meaning$() and want to
create a dictionary then you would need to sort both arrays using the alphabetical
order of the word$() array.

Instead of sorting the arrays you can create an index array, sort this using
one of the arrays and then use the sorted index to access all the arrays.
This can be quicker than sorting the actual arrays.

My procedure QuickSortIndex() does this index sort.
It works with any variable types defined in the dim statement

Code: Select all

max=10000
dim sort(max);could be defined as long, float, string etc
dim indx.l(max)


Procedure QuickSortIndex(s,e)
  i=s
  j=e
  k=indx((i+j)/2)
  Repeat
    While sort(indx(i))<sort(k): i=i+1: Wend
    While sort(indx(j))>sort(k): j=j-1: Wend
    If i<=j
      tem=indx(i): indx(i)=indx(j): indx(j)=tem
      i=i+1: j=j-1
    EndIf
  Until i>j
  If j>s:QuickSortIndex(s,j):EndIf
  If i<e:QuickSortIndex(i,e):EndIf
EndProcedure


; Example of procedure use

For i=0 To max
  sort(i)=word(i); as in the dictionary example, sort using word()
  indx(i)=i; set up initial index order
Next i
quicksortindex(0,max)

;now access element i of each array using word(indx(i)), meaning(indx(i)) etc