RE: stable sorting

new topic     » goto parent     » topic index » view thread      » older message » newer message

Matthew Lewis wrote:
> 
> > From: Juergen Luethje [mailto:eu.lue at gmx.de]
> 
> > The following code (modified after 'csort.ex') does *not* perform a
> > stable sorting.
> > 
> > ----------=----------=----------=----------=----- begin of code
> > include sort.e
> > 
> > constant MARK = 2
> > constant statistics = {
> >    {"Doe", 3},
> >    {"Einstein", 1},
> >    {"Goldberg", 1},
> >    {"Irving", 4},
> >    {"Jones", 3},
> >    {"Miller", 2},
> >    {"Neuman", 2},
> >    {"Petersen", 4},
> >    {"Smith", 2},
> >    {"Zander", 5}
> > }
> > 
> > function compare_mark (sequence a, sequence b)
> >    -- Compare two sequences (records) according to MARK.
> >    return compare(a[MARK], b[MARK])
> > end function
> 
> try:
> 
> function compare_mark (sequence a, sequence b)
>    integer c
>    -- Compare two sequences (records) according to MARK.
>    c = compare(a[MARK], b[MARK])
>    if c then
>       return c
>    end if
>    return compare(a[1],b[1])
> end function
> 
> 

Here's what I do:

----------------------
include sort.e

-- Don't call this function directly, see below
integer sort_i
function sort_by_index(object x1, object x2)
integer comp, ix
    if integer(sort_i) then
    	if sort_i > 0 then
    	    return compare(x1[sort_i],x2[sort_i])
    	else
    	    return -compare(x1[-sort_i],x2[-sort_i])
    	end if
    end if

    for j = 1 to length(sort_i)-1 do
        ix = sort_i[j]
        if ix > 0 then
        	comp = compare(x1[ix],x2[ix])
        else
        	comp = -compare(x1[-ix],x2[-ix])
        end if
        if comp != 0 then
            return comp
        end if
    end for
    ix = sort_i[length(sort_i)]
    if ix > 0 then
    	return compare(x1[ix],x2[ix])
    else
    	return -compare(x1[-ix],x2[-ix])
    end if
end function


-- This is the function you actually call.
-- s = sequence to be sorted (assumed to be at least 2-dimensional)
-- i = integer index of element (column) to sort on,
-- or sequence of indexes to sort on multiple fields
-- (in order of preference).
-- If any given index is positive, then it will sort that element in 
ascending order.
-- If negative, it will sort that element in descending order.

global function sort_by_element(sequence s,object i)
    sort_i = i
    return custom_sort(routine_id("sort_by_index"),s)
end function

new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu