Sorting Data Structures

RPG
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Previously, I discussed how to sort subfiles using the C language "qsort" function. Apparently, a lot more people need the capability to sort their data structures. So this week, I'll show you how to specifically sort a multiple-occurrence data structure or one of the new data structure arrays.

The first thing you need to do to sort multiple-occurrence data structures or data structure arrays is make sure your data structure is one of those two types. That is, the data structure must have the OCCURS or DIM keyword specified with a value greater than 1. If the value isn't greater than 1, sorting will, obviously, achieve nothing.

Sorting a data structure does not require any type of control on loading the data. You add and retrieve data from the data structure as you normally do, but instead of sorting an array using the SORTA opcode, you use the SORTDS procedure to sort your data structure.

Using qsort()

Sorting a data structure's occurrences (when using a traditional multiple-occurrence data structure) or array elements (when using the new data structure array) can be accomplished in a number of ways. The fastest and most flexible choice today is to use a procedure named "qsort()" from the C language runtime library. Like all C language functions, qsort() can be called from RPG IV rather easily.

The qsort() procedure sorts its data by arranging the elements of the data passed to it based on the return value of a subprocedure that you've written. That subprocedure name is specified on the fourth parameter of the call to qsort().

Since a multiple-occurrence data structure is similar to an array, qsort() can sort data structure occurrences just as easily as arrays. In fact, qsort() doesn't care if the value passed to it is an array, a data structure, or just a very long field with data that needs to be sorted. Let's look at the prototype for the qsort() procedure.

     D QuickSort       PR                  ExtProc('qsort')
     D  szSortDS                       *   VALUE
     D  NbrElems                     10U 0 VALUE
     D  SizeOfElem                   10U 0 VALUE
     D  CompProc                       *   VALUE ProcPtr 

The qsort() Parameters

The qsort() procedure accepts four parameters. Within these parameters, you identify the array or data structure you would like to sort, the number of elements you want to sort, the length of each element, and a subprocedure name that is called by qsort().

Variable Name

The first parameter identifies the field, array, or data structure to be sorted. Note that this parameter is a data type of * (i.e., a pointer) and is also passed by value. This means that when you specify the variable you want to sort, you must enclose that variable name with the %ADDR() built-in function. This built-in function extracts the memory address of the field, which is what is required for this parameter. We declare the parameter in this way--versus using a traditional field and field length--because we do not want to limit the size of the sorted variable to that of a field (which is currently limited to 64 K).

Number of Elements

The second parameter identifies the number of elements to be sorted. This may or may not be the number of elements in the array or data structure. It is, however, the number of elements you want to sort. This is extremely useful when the data structure or array is declared with, for example, 500 elements and you've only populated something like 75 of them. Why sort those last 425 elements when they are empty?

Actually, those empty elements would probably appear at the beginning of the sorted array if you used the traditional SORTA opcode. This problem can be completely avoided by using qsort().

Element Length

The third parameter identifies the length of each element of the array or single occurrence of the data structure. Typically, you would specify %size(myDS) or %size(myArray) for this parameter. The length of an element of the array being sorted or the length of the data structure (one occurrence) is specified.

Subprocedure

The fourth parameter is the address of a subprocedure name. This subprocedure is called by qsort() to compare two values at a time.

This subprocedure must accept two parameters. Both parameters are pointer data types that are passed by value. The subprocedure must return a 10i0 (int4) value that indicates the results of the comparison. The prototype for this subprocedure is illustrated below:

     D myCompare       PR            10I 0
     D  pValue1                        *   Value
     D  pValue2                        *   Value

When qsort() is evoked, it calls your subprocedure repeatedly. Each time it calls your subprocedure, it passes in two values. Your subprocedure compares those values and returns 1, -1, or 0. A return value of 1 means the value on the first parameter is greater than the value of the second parameter. A return value of zero indicates that the two values are equal. A return value of -1 means the value of the first parameter is less than the value of the second parameter. Below is a summary of the return values.

? 1 means Parm1 > Parm2
• 0 means Parm1 = Parm2
• -1 means Parm1 < Parm2

Besides comparing the values, the subprocedure can do anything you need. But remember that it should do whatever it does very quickly and return. Otherwise, the sorting process will be slower than it could be.

Calling qsort()

To call qsort(), you need to do two things: 1) Create a prototype for the C language 'qsort' function, and 2) link to the binding directory named QC2LE.

To create the prototype for qsort(), type in the following Definition specifications:

     D SortDS          PR                  ExtProc('qsort')
     D  szDSName                       *   VALUE
     D  NbrElems                     10U 0 VALUE
     D  ElemSize                     10U 0 VALUE
     D  CompProc                       *   VALUE ProcPtr 

To link to the QC2LE binding directory, add the BNDDIR keyword to your Header specification, as follows:

     H  BNDDIR('QC2LE')

Sorting a Data Structure

To sort a data structure, call the qsort() procedure that has been previously prototyped and pass to it the address of the data structure, the number of occurrences to sort, the length of the data structure, and the address of the name of your compare subprocedure.

In the example that follows, the data structure named MYSTUFF has an occurrence setting of 1000. There is also a field named nENTRIES that you need to use to set the number of "active" occurrences (occurrences that have data in them). You want to sort only the active occurrences, not the empty ones.

.....DName+++++++++++EUDS.......Length+TDc.Functions+++++++++++
     D MyStuff         DS                  OCCURS(1000)
     D   CustNo                       7P 0
     D   CustName                    30A
     D   Address                     30A
     D   City                        20A
     D   State                        2A
     D   PostalCode                  10A
     D   Country                     20
     D   Phone                       10A 
     D    AreaCode                    3S 0 Overlay(Phone)
     D    PhnNbr                      7S 0 Overlay(Phone:*NEXT)

     D nEntries        S             10I 0

To sort this array, you could call qsort() using the SORTDS prototype as follows:

   callp     SortDS(%addr(myStuff): nEntries :
                 %size(MyStuff) : %paddr('MYCOMPPROC'))

In the example above, the nENTRIES field must be set to the active number of occurrences in the data structure; otherwise, the call to qsort() will run very quickly and not sort your data structure.

The MYCOMPPROC subprocedure must also be created somewhere in your source member or program. Note that the name of the compare procedure is in all uppercase and enclosed in single quotes within the %PADDR() built-in function. This is required because RPG subprocedures are converted to all uppercase when they are compiled. A fundamental version of this subprocedure follows:

P myCompProc      B                   EXPORT            
D myCompProc      PI            10I 0
D  pValue1                        *   Value
D  pValue2                        *   Value

D DS1             DS                  LikeDS(MYSTUFF)
D                                     Based(pValue1)
D DS2             DS                  LikeDS(MYSTUFF)
D                                     Based(pValue2)

C                   if        DS1.CustName > DS2.CustName 
C                   return    1
C                   elseif    DS1.CustName < DS2.CustName 
C                   return    -1
C                   endif
C                   return    0
P myCompProc      E                    

I am using OS/400 V5R1 RPG IV extensions in this example, but you can easily convert it to pre-V5R1 by fully declaring the data structures with their subfields.

Sorting Decisions

There are two styles of sorting that you can achieve: 1) Sort the data structure using the same set of data each time it is sorted (that is, the same subfield is used as the "key" whenever the data structure is sorted). This is the style used in the example above. 2) Write a subprocedure that checks a global variable for some type of value and then uses that value to conditionally sort the data structure by any or all of its subfields.

The only thing you need to keep track of is the current number of elements in the array or data structure you want to sort.

If you want to sort by different subfields within the same program, you need to be more creative in the MYCOMPPROC subprocedure. My suggestion is to create a global variable and move the field name into that field. Then, in your subprocedure, check that field for the specific field name, and compare the contents of that field in the two data structures.

For example, if I want to be able to sort the MYSTUFF data structure by customer number, customer name, phone number, or ZIP code, I could have a MYCOMPPROC subprocedure that looks like the following:

     P myCompProc      B                   EXPORT        
     D myCompProc      PI            10I 0
     D  pValue1                        *   Value
     D  pValue2                        *   Value

     D DS1             DS                  LikeDS(MYSTUFF)
     D                                     Based(pValue1)
     D DS2             DS                  LikeDS(MYSTUFF)
     D                                     Based(pValue2)
     C                   Select
     C                   When      m_szSortField = 'CUSTNO' or 
     C                               m_szSortField = ' '
     C                   if        DS1.CustNo > DS2.CustNo
     C                   return    1
     C                   elseif    DS1.CustNo < DS2.CustNo
     C                   return    -1
     C                   else
     C                   return    0
     C                   endif
     
     C                   When      m_szSortField = 'CUSTNAME'
     C                   if        DS1.CustName > DS2.CustName
     C                   return    1
     C                   elseif    DS1.CustName < DS2.CustName
     C                   return    -1
     C                   else
     C                   return    0
     C                   endif

     C                   When      m_szSortField = 'PHONE'
     C                   if        DS1.Phone > DS2.Phone
     C                   return    1
     C                   elseif    DS1.Phone < DS2.Phone
     C                   return    -1
     C                   else
     C                   return    0
     C                   endif

     C                   When      m_szSortField = 'ZIPCODE'
     C                   if        DS1.ZipCode > DS2.ZipCode
     C                   return    1
     C                   elseif    DS1.ZipCode < DS2.ZipCode
     C                   return    -1
     C                   else
     C                   return    0
     C                   endif
     C                   endsl
      ** If no valid m_szSortField is detected, return equal.
     C                   return    0
     P myCompProc      E 

In this example, the global variable named M_SZSORTFIELD is used to identify the field to be used by the sort routine. Just before calling qsort(), you would set the value of this field to the name of the field by which you wanted to sort. So, for example, if you want to sort by ZIPCODE, you would move 'ZIPCODE' into m_SZSORTFIELD and then call SORTDS, as follows:

D SortDS          PR                  ExtProc('qsort')
D  szDSName                       *   VALUE
D  NbrElems                     10U 0 VALUE
D  ElemSize                     10U 0 VALUE
D  CompProc                       *   VALUE ProcPtr 

D myCompProc      PR            10I 0
D  pValue1                        *   Value
D  pValue2                        *   Value

D nEntries        S             10I 0
D m_szSortField   S             10A

C                   eval      m_szSortField = 'ZIPCODE'
C                   callp     SortDS(%addr(myStuff): nEntries :
C                              %size(MyStuff) : %paddr('MYCOMPPROC'))

The qsort() procedure is much faster and more dependable than SORTA, and it allows you to sort only those entries in the data structure or array that contain data (no need to use some silly technique like initializing the entire array with all 9s). If you can get used to using %ADDR and %PADDR, there really isn't any difficulty at all.

So give it a try!

Bob Cozzi has been programming in RPG since 1978. Since then, he has written many articles and several books, including The Modern RPG Language--the most widely used RPG reference manual in the world. Bob is also a very popular speaker at industry events such as RPG World and is the author of his own Web site and of the RPG ToolKit, an add-on library for RPG IV programmers.

BOB COZZI

Bob Cozzi is a programmer/consultant, writer/author, and software developer. His popular RPG xTools add-on subprocedure library for RPG IV is fast becoming a standard with RPG developers. His book The Modern RPG Language has been the most widely used RPG programming book for more than a decade. He, along with others, speaks at and produces the highly popular RPG World conference for RPG programmers.


MC Press books written by Robert Cozzi available now on the MC Press Bookstore.

RPG TnT RPG TnT
Get this jam-packed resource of quick, easy-to-implement RPG tips!
List Price $65.00

Now On Sale

The Modern RPG IV Language The Modern RPG IV Language
Cozzi on everything RPG! What more could you want?
List Price $99.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  •  

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: