User Tools

Site Tools

k7:k7.4:k7.4.9:k7.4.9.4:start Project - Sorting a derived array

Sorting a derived array has already been described in? chapter The serious disadvantage of the sorting described in this chapter is that you have to specify the field to be sorted by in the program. This chapter introduces a solution for sorting a derived array, which allows you to dynamically define the field by which the object array is sorted. All the explanations in –> chapter also apply to this project, especially the details of the _compare() method. The class CDS is supplemented in the project by some variables and a property. Class definition

The array to be sorted aCDSArray is, as in –> chapter, a one-dimensional, derived array whose elements are objects of a self-written class CDS. The array type is therefore CDS[] or Object[].

  • All elements of the array are of type CDS and consist in the project of the values of seven different variables with different data types declared in the class CDS.
  • The _compare () method is adjusted accordingly compared to the variant from –> chapter
  • The property SortField of the data type Integer is added to the class CDS, which can be read and write access to it, in order to be able to specify at a suitable place the field by which to sort.

File CDS. class:

[1] ' Gambas class file
[3] Public JGS As Integer
[4] Public BirthDate As Date
[5] Public FirstName As String
[6] Public Surname As String
[7] Public Latin As Boolean
[8] Public Course1 As String
[9] Public Course2 As String
[11] Public Function _compare(DS As CDS) As Integer
[13]   Select Case $SortField
[14]   Case 1
[15]     Return Sgn(JGS - DS.JGS) ' Number
[16]   Case 2
[17]      Return - Sgn(DateDiff(BirthDate, DS.BirthDate, gb.Second)) ' Date
[18]   Case 3
[19]     Return Comp(Firstname, DS.Firstname) ' String
[20]   Case 4
[21]     Return Comp(Surname, DS.Surname)
[22]   Case 5
[23]     Return IIf(Latin, IIf(DS.Latin, 0, 1), IIf(DS.Latin, -1, 0)) ' Truth value
[24]   Case 6
[25]     Return Comp(Course1, DS.Course1)
[26]   Case 7
[27]     Return Comp(Course2, DS.Course2)
[28]    Default
[29]       Error.Raise(("No sort method found!"))
[30]   End Select
[32] End
[34] Private $SortField As Integer
[35] Property SortField As Integer
[37] Private Function SortField_Read() As Integer
[38]   Return $SortField
[39] End
[41] Private Sub SortField_Write(NewValue As Integer)
[42]   If NewValue < 1 Or NewValue > 7 Then
[43]      Error.Raise(("Input error! Input only from[1..7]."))
[44]   Else
[45]     $SortField = NewValue
[46]   Endif
[47] End

The structure of the elements in the derived array aCDSArray becomes particularly clear in the project when you create a new element of the CDS array, fill it with data and insert it into the array:

hCDS = New CDS
  hCDS.JGS = 11
  hCDS.BirthDate = Date(Year(Now()) - 17, 12, 13)
  hCDS.Firstname = "Gerd"
  hCDS.Surname = "Vulutre"
  hCDS.Latin = True
  hCDS.Course1 = "Social Studies"
  hCDS.Course2 = "Chemistry"

For an array with 6 elements of type CDS, for example, the following (formatted) display of the array in the console of the IDE consists of 6 rows and 7 (fictitious) columns or fields:

11      22.08.1996      Doris   Fox      True    Biology         German
12      18.08.1997      Anna    Cat      False   Mathematics     English
11      17.06.1996      Maria   Zebra    False   Informatics     German
12      02.05.1997      Anna    Owl      False   Astronomy       Art
12      27.04.1996      Fred    Badger   False   Astronomy       German
11      13.12.1997      Gerd    Vulture  True    Social Studies  Chemistry

The following requirements are required for sorting the derived array:

  • It should be possible to sort the array by a freely selectable column (field) - for example by last names.
  • As is usual for sorting, you should be able to specify a sort sequence using one of the two constants gb. ascent (0) (default) for an ascending or gb. descent (16) for a descending sort sequence. Approach to the implementation of claims

Instead of the possible array class CDS[] - which would be created automatically by the interpreter and thus have all properties and methods of an array - the class Object[] is used in the project. This is possible because all elements of the array to be sorted are objects of the class CDS. To eliminate the disadvantage of being able to specify only statically the field to be sorted by, the class Object[] is extended by a method to sort multi-dimensionally. Benoît Minisini points out that you cannot directly overwrite the class Object[] because '[' and']' are not allowed in project filenames. He therefore suggests that all methods and properties of the class Object[] are inherited in a new class via Inherits Object[] and enhancements are implemented there. At all points in the project, the new class replaces the class Object[].

The source code of the new class CDSArray in the file CDSArray. class is easy to review:

[1] ' Gambas class file
[3] Inherits Object[]
[5] Public Sub SortNew(Field As Integer, Optional Mode As Integer)
[6]   Dim iIndex As Integer
[8]   If Super.Count = 0 Then Return
[10]   For iIndex = 0 To Super.Count - 1
[11]     Super[iIndex].SortField = Field
[12]   Next
[14]   Super.Sort(Mode)
[16] End


  • To avoid duplicating any source code that already exists in gambas, the new class CDSArray is based on the class Object[] - which represents an array of objects.
  • The class' CDSArray' in line 3 inherits all methods and properties of the class Object[].
  • The method SortNew (Field As Integer, Optional Mode As Integer) is added to the class CDSArray in lines 5 to 16.
  • The method SortNew (..) is simple. It first checks whether there are elements in the array to be sorted that can be sorted. In this case, the SortField property is set in all elements, because this property is part of the extension of the class CDS, which later controls the sorting. Using the special object Super allows access to the data of Object[] from which the CDSArray class is derived. This accesses each CDS object contained in the object.
  • If the SortField property of all elements of type CDS is set, the ordinary Object[].sort([ Mode As Integer]) method sorts after the optional' Mode' parameter has been used to set the sort order.

What has been achieved so far?

On the one hand, the class CDS is available to you as a data container with _compare () method and the property SortField, and on the other hand, the new class CDSArray, which overwrites the class Object[] and provides a method in the SortNew () method, in which you can use the property SortField to specify the field according to which you want to sort and optionally the sort sequence.

The two classes CDS and CDSArray are used in the main program. An array aCDSArray of the class CDSArray is generated, filled with data in different ways and sorted according to a freely selectable field, and the contents of the original and sorted array are displayed:

' Gambas class file
Public aCDSArray As CDSArray
Public iAsDescent As Integer = 0
Public Sub Form_Open()
  FMain.Resizable = False
  rbtnAscent.Value = True
End ' Form_Open()
Public Sub btnClassArray_Click()
  Dim iCount As Integer
  Dim hCDS As CDS
  Dim aNames As String[] = ["Eagle", "Bear", "Badger", "Fox", "Tit", "Owl", "Zebra"]
  Dim aSurNames As String[] = ["Anna", "Bruno", "Doris", "Fred", "Maria", "Klaus", "Udo"]
  Dim aCourses1 As String[] = ["Mathematics", "History", "Astronomy", "Biology", "Informatics"]
  Dim aCourses2 As String[] = ["German", "Physics", "English", "Art", "Music"]
  aCDSArray = New CDSArray
  For iCount = 0 To 4
    hCDS = New CDS
      hCDS.JGS = CInt(Rnd(11, 13)) ' 11..12
    ' Random date: Year: matching JGS, Month: 1..12, Tag: 1..28 (this always fits...)
      hCDS.BirthDate = Date(Int(Rnd(Year(Now()) - 18, Year(Now()) - 16)), Int(Rnd(1, 13)), Int(Rnd(1, 29)))
      hCDS.Firstname = aSurNames[Int(Rnd(0, aSurNames.Count))]
      hCDS.Surname = aNames[Int(Rnd(0, aNames.Count))]
      hCDS.Latin = CBool(Round(Rnd(0, 1)))
      hCDS.Course1 = aCourses1[Int(Rnd(0, aCourses1.Count))]
      hCDS.Course2 = aCourses2[Int(Rnd(0, aCourses2.Count))]
  Next ' iCount
  hCDS = New CDS        ' Generate a new but empty array element of object type CDS...
  aCDSArray.Add(hCDS)   ' ... and paste it into the array
' Overwrite the last array element with the following data:
  aCDSArray[aCDSArray.Max].JGS = 11
  aCDSArray[aCDSArray.Max].BirthDate = Date(Year(Now()) - 17, 12, 13)
  aCDSArray[aCDSArray.Max].Firstname = "Gerd"
  aCDSArray[aCDSArray.Max].Surname = "Volture"
  aCDSArray[aCDSArray.Max].Latin = True
  aCDSArray[aCDSArray.Max].Course = "Social Studies"
  aCDSArray[aCDSArray.Max].Course2 = "Chemistry"
' Display all records
' Sortierung Array:
' First parameter: Field number of the field to be sorted by (SpinBox)
' 2nd parameter: Determination of the sorting order (optional) (RadioButton)
  aCDSArray.SortNew(spinBox.Value, iAsDescent) ' → Field 4 (Surname), descending (Z..a)
End ' btnClassArray_Click()
Private Sub ShowCDSArrayElements(aArray As CDSArray)
  Dim hCDS As CDS
  Dim i As Integer
' Display of all data sets (Console of the IDE)
  For Each hCDS In aArray
    Print hCDS.JGS,
    Print Format(hCDS.BirthDate, ""),
    Print hCDS.Firstname,
    Print hCDS.Surname,
    Print hCDS.Latin,
    Print hCDS.Course1,
    Print hCDS.Course2
  Next ' hCDS
' Variante 2
' For i = 0 To aArray.Max
'   Print aArray[i].JGS,
'   Print Format(aArray[i].BirthDate, ""),
'   Print aArray[i].Firstname,
'   Print aArray[i].Surname,
'   Print aArray[i].Latin,
'   Print aArray[i].Course1,
'   Print aArray[i].Course2
' Next
' Print
End ' ShowCDSArrayElements(aArray As ObjectSort)
Public Sub rbtnAscent_Click()
  iAsDescent = gb.Ascent
End ' rbtnAscent_Click()
Public Sub rbtnDescent_Click()
  iAsDescent = gb.Descent
End ' rbtnDescent_Click()

Output of the original and sorted array - sorted by surname (descending) - in the console of the IDE:

11      22.08.1996      Doris   Fox      True    Biology         German
12      18.08.1997      Anna    Cat      False   Mathematics     English
11      17.06.1996      Maria   Zebra    False   Informatics     German
12      02.05.1997      Anna    Owl      False   Astronomy       Art
12      27.04.1996      Fred    Badger   False   Astronomy       German
11      13.12.1997      Gerd    Vulture  True    Social Studies  Chemistry
11      17.06.1996      Maria   Zebra    False   Informatics      German
12      02.05.1997      Anna    Owl      False   Astronomy        Art
12      18.08.1997      Anna    Cat      False   Mathematics      English
11      13.12.1997      Gerd    Vulture  True    Social Studies   Chemistry
11      22.08.1996      Doris   Fox      True    Biology          German
12      27.04.1996      Fred    Badger   False   Astronomy        German


The website uses a temporary session cookie. This technically necessary cookie is deleted when the browser is closed. You can find information on cookies in our privacy policy.
k7/k7.4/k7.4.9/k7.4.9.4/start.txt · Last modified: 05.02.2022 (external edit)

Page Tools