Last active
March 15, 2022 20:30
-
-
Save akshaymnair/00a060b51d6d4e47fbc9d3dfcf99ef14 to your computer and use it in GitHub Desktop.
Alphanumeric Sorting in Java, Sort a given String Array in Natural Order
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
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.Collections; | |
import java.util.Comparator; | |
import java.util.List; | |
public class FB { | |
public static int comparator(String s1, String s2) { | |
String[] pt1 = s1.split("((?<=[a-z])(?=[0-9]))|((?<=[0-9])(?=[a-z]))"); | |
String[] pt2 = s2.split("((?<=[a-z])(?=[0-9]))|((?<=[0-9])(?=[a-z]))"); | |
//pt1 and pt2 arrays will have the string split in alphabets and numbers | |
int i=0; | |
if(Arrays.equals(pt1, pt2)) | |
return 0; | |
else{ | |
for(i=0;i<Math.min(pt1.length, pt2.length);i++) | |
if(!pt1[i].equals(pt2[i])) { | |
if(!isNumber(pt1[i],pt2[i])) { | |
if(pt1[i].compareTo(pt2[i])>0) | |
return 1; | |
else | |
return -1; | |
} | |
else { | |
int nu1 = Integer.parseInt(pt1[i]); | |
int nu2 = Integer.parseInt(pt2[i]); | |
if(nu1>nu2) | |
return 1; | |
else | |
return -1; | |
} | |
} | |
} | |
if(pt1.length>i) | |
return 1; | |
else | |
return -1; | |
} | |
private static Boolean isNumber(String n1, String n2) { | |
// TODO Auto-generated method stub | |
try { | |
int nu1 = Integer.parseInt(n1); | |
int nu2 = Integer.parseInt(n2); | |
return true; | |
} | |
catch(Exception x) { | |
return false; | |
} | |
} | |
public static void main(String[] args) { | |
// TODO Auto-generated method stub | |
String[] examples = {"1some", "2some", "20some", "21some", "3some", "some", "1abc", "abc"}; | |
List<String> values = new ArrayList<String>(Arrays.asList(examples)); | |
System.out.println(values); | |
Comparator<String> com = (o1,o2) -> {return comparator(o1,o2);}; //lambda expression | |
Collections.sort(values,com); | |
System.out.println(values); | |
} | |
} |
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
input: [aa9, a, 9, a9a, 9aa, abc, 999, 9a9] | |
output:[9, 9a9, 9aa, 999, a, a9a, aa9, abc] | |
input: [1some, 2some, 20some, 21some, 3some, some, 1abc, abc] | |
output:[1abc, 1some, 2some, 3some, 20some, 21some, abc, some] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can we add sorting to this such that numbers with special characters like for eg: --"-01234 are also sorted in addition to Alpha numeric characters.