Created
August 20, 2014 16:13
-
-
Save MorganConrad/dae68853c2854c7a0c58 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.flyingspaniel.xen; | |
import java.util.Arrays; | |
import java.util.Comparator; | |
/** | |
* @author Morgan Conrad | |
* @see <a href="http://opensource.org/licenses/MIT">This software is released under the MIT License</a> | |
* @since Copyright (c) 2014 by Morgan Conrad | |
*/ | |
public class SO25396760 implements Comparator<String> { | |
@Override | |
public int compare(String s1, String s2) { | |
int minLength = Math.min(s1.length(), s2.length()); | |
int result = s1.substring(0, minLength).compareTo(s2.substring(0, minLength)); | |
if (result != 0) | |
return result; | |
int lenDiff = s1.length() - s2.length(); | |
if (lenDiff == 0) | |
return 0; // Strings are equal | |
if (lenDiff < 0) | |
return compare(s1, s2.substring(minLength)); | |
else | |
return compare(s1.substring(minLength), s2); | |
} | |
public static void main(String[] args) { | |
String[] array = {"321","3","35", "321334", "333", "2"}; | |
SO25396760 sorter = new SO25396760(); | |
Arrays.sort(array, sorter); | |
System.out.println(Arrays.toString(array)); // [2, 321, 321334, 3, 333, 35] | |
String result = ""; | |
for (String s : array) | |
result += s; | |
System.out.println(result); // 2321321334333335 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment