Manage Learn to apply best practices and optimize your operations.

Selection Sort, Binary Search, And Merge-Sort Routines


Sub SelectionSort (MyArray As Variant)
If Ubound (MyArray) <= 0 Then Exit Sub

' Selection Sort, "Data Structures Using C", Tenenbaum, ..., p. 337.

nElem = Ubound (MyArray) + 1
For i = nElem - 1 To 1 Step -1
Large$ = MyArray(0)
indx = 0
For j = 1 To nElem
If j > i Then Exit For
If Strcompare(MyArray(j), Large$) > 0 Then ' Ascending order
Large$ = MyArray(j)
indx = j
End If
Next
MyArray(indx) = MyArray(i)
MyArray(i) = Large$
Next
End Sub




Function libBinarySearch (MyValue As String, MyArray As Variant, ValuePos As
Integer) As
Integer
' "Data Structures Using C", A. Tenenbaum, ..., p. 379

libBinarySearch = False

Dim low, hi, midpoint, n As Integer

n = Ubound(MyArray) + 1
low = 0
hi = n - 1

Do While low <= hi
midpoint = (low + hi) \ 2
If MyValue = MyArray(midpoint) Then
ValuePos = midpoint
libBinarySearch = True
Exit Function
End If
If MyValue < MyArray(midpoint) Then
hi = midpoint - 1
Else
low = midpoint + 1
End If
Loop
End Function



Function libMergeSort (a As Variant, b As Variant) As Variant
' Accepts two sorted arrays and merges them into a third sorted array.
' "Data Structures Using C", A. Tenenbaum, ..., p. 358

Dim n1, n2, n3 As Integer

n1 = Ubound(a) + 1
n2 = Ubound(b) + 1
n3 = n1 + n2

Redim c(n3 - 1) As Variant

Dim apoint, bpoint, cpoint As Integer
Dim alimit, blimit, climit As Integer

alimit = n1 - 1
blimit = n2 - 1
climit = n3 - 1

apoint = 0
bpoint = 0
cpoint = 0

Do While apoint <= alimit And bpoint <= blimit
If a(apoint) < b(bpoint) Then
c(cpoint) = a(apoint)
apoint = apoint + 1
Else
c(cpoint) = b(bpoint)
bpoint = bpoint + 1
End If
cpoint = cpoint + 1
Loop

Do While apoint <= alimit
c(cpoint) = a(apoint)
cpoint = cpoint + 1
apoint = apoint + 1
Loop

Do While bpoint <= blimit
c(cpoint) = b(bpoint)
cpoint = cpoint + 1
bpoint = bpoint + 1
Loop

libMergeSort = c
End Function

Dig Deeper on Domino Resources - Part 4

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.

-ADS BY GOOGLE

SearchWindowsServer

Search400

  • iSeries tutorials

    Search400.com's tutorials provide in-depth information on the iSeries. Our iSeries tutorials address areas you need to know about...

  • V6R1 upgrade planning checklist

    When upgrading to V6R1, make sure your software will be supported, your programs will function and the correct PTFs have been ...

  • Connecting multiple iSeries systems through DDM

    Working with databases over multiple iSeries systems can be simple when remotely connecting logical partitions with distributed ...

SearchDataCenter

SearchContentManagement

Close