Sign in to follow this  
Followers 0
LxP

ArrayCustomSort()

3 posts in this topic

#1 ·  Posted (edited)

ArrayCustomSort

Sorts an array by values using a user-defined comparison function. If you wish to sort an array by some non-trivial criteria, you should use this function.

ArrayCustomSort(ByRef $Array, $FuncName[, $Start])

Requirements: AutoIt v3.1.1.56+.

Return value: False for failure; True otherwise.

@Error codes:

  • 0: No error.
  • 1: Invalid comparison function supplied.
Remarks
  • $Start specifies the array index at which to begin sorting. If omitted, sorting will take place from the very first element.
  • The comparison function must accept two arguments and return True (or a non-zero integer) if the first argument should appear at a lower index in the array than the second.
Func ArrayCustomSort(ByRef $Array, $Func, $Start = 0)
    For $I = $Start To UBound($Array) - 2
        Local $Swap = $I
        For $J = $I + 1 To UBound($Array) - 1
            If Execute($Func & '($Array[$J], $Array[$Swap])') Then $Swap = $J
            If @Error Then
                SetError(1)
                Return False
            EndIf
        Next
        If $Swap <> $I Then
            Local $Temp = $Array[$I]
            $Array[$I] = $Array[$Swap]
            $Array[$Swap] = $Temp
        EndIf
    Next
    Return True
EndFunc

Edit: Small optimisation.

Edited by LxP

Share this post


Link to post
Share on other sites



#2 ·  Posted (edited)

Example to sort an array by descending string length:

Func Shorter($1, $2)
    Return StringLen($1) > StringLen($2)
EndFunc

#Include <Array.au3>
Local $Array[5] = ['ccc', 'dddd', 'bb', 'eeeee', 'a']
_ArrayDisplay($Array, 'Unsorted')
ArrayCustomSort($Array, 'Shorter')
_ArrayDisplay($Array, 'Sorted')

Edit: Didn't I say descending?

Edited by LxP

Share this post


Link to post
Share on other sites

Example to sort an array of people's names by ascending surname:

Func ComesBefore($Name1, $Name2)
    Local $Surname1 = StringTrimLeft($Name1, StringInStr($Name1, ' ', False, -1))
    Local $Surname2 = StringTrimLeft($Name2, StringInStr($Name2, ' ', False, -1))
    Return $Surname1 < $Surname2
EndFunc

#Include <Array.au3>
Local $Array[5] = ['Alex Peters', 'Colonel Sanders', 'Jim Bob Jones', 'Jonathan Bennett', 'Mister Mister']
_ArrayDisplay($Array, 'Unsorted')
ArrayCustomSort($Array, 'ComesBefore')
_ArrayDisplay($Array, 'Sorted')

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0