Jump to content

Sort stability: Difference between revisions

no edit summary
No edit summary
No edit summary
Line 169:
=={{header|MATLAB}}==
MathWorks' policy seems to be that their built-in sorting algorithm will always be a stable sort across all versions ([http://www.mathworks.com/company/newsletters/news_notes/dec04/adventure.html reference]). To check to see if your version of MATLAB provides a stable sort type "sort" into the command line. Then highlight the text and right-click it and select "Open Selection" in the pop-up menu. This will open the source code for the sort function, the comments of which should tell you if the sort algorithm they use is stable.
 
=={{header|NetRexx}}==
Java's [http://java.sun.com/javase/6/docs/api/java/util/Collections.html#sort(java.util.List) Collections.sort()] and [http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#sort(java.lang.Object%5B%5D) Arrays.sort()] methods are guaranteed stable.
 
<lang NetRexx>/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
 
class RCSortStability
 
method main(args = String[]) public constant
 
cityList = [String "UK London", "US New York", "US Birmingham", "UK Birmingham"]
 
cn = String[cityList.length]
 
say
say "Before sort:"
System.arraycopy(cityList, 0, cn, 0, cityList.length)
loop city = 0 to cn.length - 1
say cn[city]
end city
 
cCompNm = Comparator CityComparator()
Arrays.sort(cn, cCompNm)
 
say
say "After sort on city:"
loop city = 0 to cn.length - 1
say cn[city]
end city
 
say
say "Before sort:"
System.arraycopy(cityList, 0, cn, 0, cityList.length)
loop city = 0 to cn.length - 1
say cn[city]
end city
 
cCompCtry = Comparator CountryComparator()
Arrays.sort(cn, cCompCtry)
 
say
say "After sort on country:"
loop city = 0 to cn.length - 1
say cn[city]
end city
say
 
return
 
class RCSortStability.CityComparator implements Comparator
 
method compare(lft = Object, rgt = Object) public binary returns int
return (String lft).substring(4).compareTo((String rgt).substring(4))
 
class RCSortStability.CountryComparator implements Comparator
 
method compare(lft = Object, rgt = Object) public binary returns int
return (String lft).substring(0, 2).compareTo((String rgt).substring(0, 2))
</lang>
;Output
<pre>
Before sort:
UK London
US New York
US Birmingham
UK Birmingham
 
After sort on city:
US Birmingham
UK Birmingham
UK London
US New York
 
Before sort:
UK London
US New York
US Birmingham
UK Birmingham
 
After sort on country:
UK London
UK Birmingham
US New York
US Birmingham
</pre>
 
=={{header|OCaml}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.