Skip to content

Instantly share code, notes, and snippets.

@asilchev
Created April 26, 2022 19:56
Show Gist options
  • Save asilchev/cc6ff6983dbb2f472e498cc7fa2cf1ea to your computer and use it in GitHub Desktop.
Save asilchev/cc6ff6983dbb2f472e498cc7fa2cf1ea to your computer and use it in GitHub Desktop.
package org.sv.sandbox;
import java.util.Arrays;
import java.util.Comparator;
public class VersionComparator implements Comparator<String> {
char[] alpha = new char[] {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r'
, 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
@Override
public int compare(String versionA, String versionB) {
if(versionA == null)
return 1;
if(versionB == null)
return -1;
String[] thisParts = versionA.split("\\.");
String[] thatParts = versionB.split("\\.");
int length = Math.max(thisParts.length, thatParts.length);
for(int i = 0; i < length; i++) {
int thisPart = i < thisParts.length ?
prepareVersion(thisParts[i]) : 0;
int thatPart = i < thatParts.length ?
prepareVersion(thatParts[i]) : 0;
if(thisPart < thatPart)
return -1;
if(thisPart > thatPart)
return 1;
}
return 0;
}
private int prepareVersion(String version) {
if (!version.contains("-")) {
return Integer.parseInt(version);
}
String[] parts = version.split("-");
int weight = alpha.length - Arrays.binarySearch(alpha, parts[1].charAt(0));
return Integer.parseInt(parts[0]) - (weight + 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment