Ralph Zbrog
New User
Joined: 21 Nov 2009 Posts: 58 Location: California
|
|
|
|
In a previous thread, Sid_ibm asked how to sort a set of numbers. Atulbagewadikar provided Natural code for a simple bubble sort, but noted that this was not the most efficient solution. This is quite true. In fact even an optimized double-bubble sort will give you poor performance.
The way to sort an array is via Natural's SORT statement. This technique can be used on-line with fairly large tables.
Typically you have a key and associated data, so here's sample code to sort such an array. The solutions are extracted from my Intermediate Natural training course. The first program is for tables where key and data are defined and initialized separately. The second example is where the key and data are defined as a single entity. In either case the same subprogram is called to perform the sort.
The point to note is that you need a unique sorting subprogram for each combination of key/data format and length.
Program SORTP1 - separate KEY and DATA:
Code: |
DEFINE DATA
LOCAL
1 #MAX (I4) CONST <10>
1 #KEY (A15/#MAX) INIT <'Smith', 'Jones', 'Able',
'Charles', ' ', 'Baker'>
1 #OTHER (A25/#MAX) INIT <'Jane', 'Andrew', 'Michael',
'Alice', ' ', 'Margaret'>
1 #TOP (I4) INIT <6>
END-DEFINE
*
DISPLAY
#MAX
#TOP
#KEY (1:#TOP)
#OTHER (1:#TOP)
CALLNAT "SORTN" #KEY (1:#TOP) /* (1:#MAX)
#OTHER (1:#TOP) /* (1:#MAX)
#TOP
SKIP 1
DISPLAY
#MAX
#TOP
#KEY (1:#TOP)
#OTHER (1:#TOP)
END
|
Program SORTP2 - combined KEY and DATA:
Code: |
DEFINE DATA
LOCAL
1 #MAX (I4) CONST <10>
1 #TBL (A40/#MAX) INIT <'Smith ' - 'Jane'
,'Jones ' - 'Andrew'
,'Able ' - 'Michael'
,'Charles ' - 'Alice'
,' ' - ' '
,'Baker ' - 'Margaret'
>
1 REDEFINE #TBL
2 #ENTRY (#MAX)
3 #KEY (A15)
3 #OTHER (A25)
1 #TOP (I4) INIT <6>
END-DEFINE
*
DISPLAY
#MAX
#TOP
#KEY (1:#TOP)
#OTHER (1:#TOP)
CALLNAT "SORTN" #KEY (1:#TOP) /* (1:#MAX)
#OTHER (1:#TOP) /* (1:#MAX)
#TOP
SKIP 1
DISPLAY
#MAX
#TOP
#KEY (1:#TOP)
#OTHER (1:#TOP)
END |
Subprogram SORTN as a bit of extra code to eliminate blank entries:
Code: |
DEFINE DATA
PARAMETER
1 #KEY (A15/1:V)
1 #OTH (A25/1:V)
1 #T (I4)
LOCAL
1 #SORT (A15)
1 #OTHER (A25)
1 #I (I4)
1 #M (I4)
END-DEFINE
*
ASSIGN #M = *OCC (#KEY)
FOR #I = 1 #M
ASSIGN #SORT = #KEY (#I)
ASSIGN #OTHER = #OTH (#I)
END-ALL
*
SORT BY #SORT
USING #OTHER
AT START OF DATA
RESET #I
#KEY (*)
#OTH (*)
END-START
/*
IF #SORT <> ' '
AND #OTHER <> ' '
THEN
ADD 1 TO #I
ASSIGN #KEY (#I) = #SORT
ASSIGN #OTH (#I) = #OTHER
END-IF
END-SORT
ASSIGN #T = #I
END |
Both programs display the same results:
Code: |
Page 1 04/15/10
#MAX #TOP #KEY #OTHER
----------- ----------- --------------- -------------------------
10 6 Smith Jane
Jones Andrew
Able Michael
Charles Alice
Baker Margaret
10 5 Able Michael
Baker Margaret
Charles Alice
Jones Andrew
Smith Jane |
|
|