WinBatch Tech Support Home

Database Search

If you can't find the information using the categories below, post a question over in our WinBatch Tech Support Forum.

TechHome

Binary Functions

Can't find the information you are looking for here? Then leave a message over on our WinBatch Tech Support Forum.

Binary Sort Two Different Fields


Question:

I have a file that needs to be sorted on two fields. The first sort would be the date field and the second field would be the time field all in descending order. As you can see below the time field comes before the date field. In SyncSort I could do something like this (30,12,bi,d,18,5,bi,d) where position 30 for 12 descending and then sort from position 18 for 5. How would I accomplish this with Winbatch?
:SortDateDescending
;sort buffer2 by date descending
RecSize=82 ;accounted for the @crlf in the record
DateOffset=30
DateSize=12
TimeOffset=18
TimeSize=5
BinarySort(buffer2,RecSize,TimeOffset,TimeSize,@STRING|@Descending)
BinarySort(buffer2,RecSize,DateOffset,DateSize,@STRING|@Descending)
return

Answer:

SyncSort is an advanced, adaptive sorting utility that works out the best way to sort a file based on the requirements you present. In cases such as your example, SyncSort actually performs a multi-pass sort and merge.

Conversely, the BinarySort function implements the classic BinarySort algorithm, which has been around since at least the 1970's. BinarySort will not maintain the sequencing from the first sort when you perform the second sort because each sort starts from scratch. Binary sort is, by definition, a one-key sort. You will need to create a third field that is the concatenation of the two sort fields, then perform a binary sort on that key.

Further complicating matters is the requirement to sort one key ascending and the other key descending. The only way I know to accomplish this is to reverse the key that you want to sort descending. For character data, the fastest way to do this is to perform the following calculation on each character in the key.

Char = Num2Char ( 256 - Char2Num ( Char ) )
In the above formula, Char is one character, extracted by iteratively extracting one character at a time from the string.

The loop might look something like this.

NewKey = ''
for J = 1 to StrLen ( key )
Char = StrSub ( key , J , 1 )
NewChar = Num2Char ( 256 - Char2Num ( Char ) )
NewKey = StrCat ( NewKey , NewChar )
next
You must repeat the above loop for each record in the set.
Article ID:   W16387
File Created: 2005:02:18:12:20:16
Last Updated: 2005:02:18:12:20:16