Sort stability: Difference between revisions

Line 127:
=={{header|Java}}==
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.
 
The following sample demonstrates Java's sort stability:
<lang Java>import java.util.Arrays;
import java.util.Comparator;
 
public class RJSortStability {
 
private static final String[] cityList;
 
static {
cityList = new String[] { "UK London", "US New York", "US Birmingham", "UK Birmingham", };
}
 
public RJSortStability() {
return;
}
 
public static void main(String[] args) {
 
String[] cn;
 
cn = new String[cityList.length];
System.arraycopy(cityList, 0, cn, 0, cityList.length);
System.out.println();
System.out.println("Before sort:");
for (String city : cn) {
System.out.println(city);
}
 
Comparator<String> cCompNm = new CityComparator();
Arrays.sort(cn, cCompNm
);
 
System.out.println();
System.out.println("After sort on city:");
for (String city : cn) {
System.out.println(city);
}
 
cn = new String[cityList.length];
System.arraycopy(cityList, 0, cn, 0, cityList.length);
System.out.println();
System.out.println("Before sort:");
for (String city : cn) {
System.out.println(city);
}
 
Comparator<String> cCompCtry = new CountryComparator();
Arrays.sort(cn, cCompCtry);
 
System.out.println();
System.out.println("After sort on country:");
for (String city : cn) {
System.out.println(city);
}
 
System.out.println();
 
return;
}
 
static class CityComparator implements Comparator<String> {
public int compare(String lft, String rgt) {
return lft.substring(4).compareTo(rgt.substring(4));
}
}
 
static class CountryComparator implements Comparator<String> {
public int compare(String lft, String rgt) {
return lft.substring(0, 2).compareTo(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|JavaScript}}==
Anonymous user