Skip to content

Instantly share code, notes, and snippets.

@jackganzha
Created March 25, 2011 04:51
Show Gist options
  • Save jackganzha/886382 to your computer and use it in GitHub Desktop.
Save jackganzha/886382 to your computer and use it in GitHub Desktop.
a natural sort implementation using ruby
def first_number_occurrence_for(string)
string.match(/(\d+)/).captures.first.to_i
end
def natural_sort(items)
items.sort { |a, b| first_number_occurrence_for(a) <=> first_number_occurrence_for(b) }
end
natural_sort ["z123.txt", "z1.txt", "z100.txt", "z200.txt", "z3.txt"]
public class NaturalSort {
public static Integer firstNumberOccurrenceFor(String string) {
java.util.regex.Matcher matcher = java.util.regex.Pattern.compile("^\\D*(\\d+).*").matcher(string);
matcher.find();
return Integer.valueOf(matcher.group(1));
}
public static java.util.List<String> naturalSort(java.util.List<String> items) {
java.util.List<String> sortedItems = new java.util.ArrayList<String>(items);
java.util.Collections.sort(sortedItems, new java.util.Comparator<String>() {
public int compare(String a, String b) {
return firstNumberOccurrenceFor(a).compareTo(firstNumberOccurrenceFor(b));
}
});
return sortedItems;
}
public static void main(String[] args) {
System.out.println(naturalSort(java.util.Arrays.asList("z123.txt", "z1.txt", "z100.txt", "z200.txt", "z3.txt")));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment