117 lines
2.6 KiB
Plaintext
117 lines
2.6 KiB
Plaintext
module Sort_an_array_of_composite_structures{
|
|
Class Quick {
|
|
Private:
|
|
module quicksort (&a()) {
|
|
do If Stackitem()>=Stackitem(2) Then Drop 2:if empty then exit else continue
|
|
over 2,2
|
|
Read p, r : i = p-1 : x=a(r)
|
|
For j=p to r-1:If .LE(a(j), x) Then i++:Swap a(i),a(j)
|
|
Next j : Swap a(i+1), a(r) : Push i+2, i:shift 3
|
|
always
|
|
}
|
|
Public:
|
|
// a and b can be strings or numbers
|
|
LE=Lambda (a, b)->a<=b
|
|
// this is final, we can't change it
|
|
Function Final Sort(&a(), a_min, a_max){
|
|
stack new {
|
|
.quicksort &a(), a_min, a_max
|
|
}
|
|
}
|
|
}
|
|
Class item {
|
|
a$, b
|
|
Class:
|
|
module item (.a$, .b) {
|
|
}
|
|
}
|
|
Data item("Joe", 5531)
|
|
Data item("Adam", 2341)
|
|
Data item("Bernie", 122)
|
|
Data item("Walter", 1234)
|
|
Data item("David", 19)
|
|
dim a()
|
|
a()=array([])
|
|
mysort=Quick()
|
|
mysort.LE=lambda (a, b)->a.a$<=b.a$
|
|
REM { ' if we want sort on second field when the first are equal (same key)
|
|
mysort.LE=lambda (a, b)->{
|
|
if a.a$=b.a$ Then
|
|
=a.b<=b.b
|
|
else
|
|
=a.a$<b.a$
|
|
end if
|
|
}
|
|
}
|
|
print "Unsorted Pairs:"
|
|
gosub display
|
|
print
|
|
call mysort.sort(&a(), 0, len(a())-1)
|
|
print "Sorted Pairs:"
|
|
gosub display
|
|
end
|
|
display:
|
|
for i=0 to len(a())-1
|
|
Print format$("{0:10} {1::-5}", a(i).a$, a(i).b)
|
|
next
|
|
return
|
|
}
|
|
Sort_an_array_of_composite_structures
|
|
Pint
|
|
module Checkit2 {
|
|
Inventory Alfa="Joe":=5531, "Adam":=2341, "Bernie":=122
|
|
Append Alfa, "Walter":=1234, "David":=19
|
|
Sort Alfa
|
|
k=Each(Alfa)
|
|
While k {
|
|
Print eval$(Alfa, k^), Eval(k)
|
|
}
|
|
}
|
|
Checkit2
|
|
Print
|
|
module Checkit3 {
|
|
class any {
|
|
x
|
|
class:
|
|
Module any (.x) {}
|
|
}
|
|
Inventory Alfa="Joe":=any(5531), "Adam":=any(2341), "Bernie":=any(122)
|
|
Append Alfa, "Walter":=any(1234), "David":=any(19)
|
|
Sort Alfa
|
|
k=Each(Alfa)
|
|
While k {
|
|
' k^ is the index number by k cursor
|
|
' Alfa("joe") return object
|
|
' Alfa(0!) return first element object
|
|
' Alfa(k^!) return (k^) objext
|
|
Print eval$(Alfa, k^), Alfa(k^!).x
|
|
}
|
|
}
|
|
Checkit3
|
|
|
|
Module Sort2Darray {
|
|
const ascending=0, descending=1
|
|
const Names=0, Rate=1
|
|
flush
|
|
Data "Bernie", 1
|
|
Data "Adam", 2341
|
|
Data "David", 19
|
|
Data "Bernie", 5
|
|
Data "Joe", 5531
|
|
Data "Walter", 1234
|
|
Data "Bernie", 122
|
|
k=stack.size/2
|
|
dim a(k,2)
|
|
Pen 15 {Print "Fill Array"}
|
|
for i=0 to k-1: read a(i,0), a(i,1): next
|
|
Pen 15 {Print "Unsorted"}
|
|
for i=0 to k-1: ? a(i,0), a(i,1): next
|
|
' there is a special sort for 2D arrays
|
|
profiler
|
|
sort a(),0,k-1,Names, ascending, Rate, descending
|
|
print timecount
|
|
Pen 15 {Print "Sorted"}
|
|
for i=0 to k-1: ? a(i,0), a(i,1): next
|
|
}
|
|
Sort2Darray
|