16
Tue, Jul
4 New Articles

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

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • 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.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • 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

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • 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: