Created
April 26, 2022 19:56
-
-
Save asilchev/cc6ff6983dbb2f472e498cc7fa2cf1ea 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 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