Compare two Version numbers - GeeksforGeeks

04 Mar, 2022
A version number is a string that is used to identify the unique state of a software product. A version number looks like a.b.c.d, where a, b, etc are numbers, so the version number is a string in which numbers are separated by dots. These numbers generally represent the hierarchy from major to minor (a is major and d is minor). In this problem, we are given two version numbers. We need to compare them and conclude which one is the latest version number (that is, which version number is greater). 
Example: 
Input: 
V1 = “1.0.31”
V2 = “1.0.27”
Output:  v1 is latest
Because V2 < V1

Input: 
V1 = “1.0.10”
V2 = “1.0.27”
Output:  v2 is latest
Because V1 < V2 
Approach: It is not possible to compare them directly because of the dot, but the versions can compare numeric part wise and then the latest version can be found. Traverse through strings and separate numeric parts and compare them. If equal, then the next numeric part is compared and so on until they differ, otherwise flag them as equal. Implement a method to compare the two versions. If there are more than two versions, then the below versionCompare method can be used as a compare method of sort method, which will sort all versions according to the specified comparison. 
C++
Java
Python3
C#
Javascript
// C/C++ program to compare// two version number#include <bits/stdc++.h>using namespace std; // Method to compare two versions.// Returns 1 if v2 is smaller, -1// if v1 is smaller, 0 if equalint versionCompare(string v1, string v2){    // vnum stores each numeric    // part of version    int vnum1 = 0, vnum2 = 0;     // loop until both string are    // processed    for (int i = 0, j = 0; (i < v1.length()                            || j < v2.length());) {        // storing numeric part of        // version 1 in vnum1        while (i < v1.length() && v1[i] != '.') {            vnum1 = vnum1 * 10 + (v1[i] - '0');            i++;        }         // storing numeric part of        // version 2 in vnum2        while (j < v2.length() && v2[j] != '.') {            vnum2 = vnum2 * 10 + (v2[j] - '0');            j++;        }         if (vnum1 > vnum2)            return 1;        if (vnum2 > vnum1)            return -1;         // if equal, reset variables and        // go for next numeric part        vnum1 = vnum2 = 0;        i++;        j++;    }    return 0;} // Driver method to check above// comparison functionint main(){    string version1 = "1.0.3";    string version2 = "1.0.7";     if (versionCompare(version1, version2) < 0)        cout << version1 << " is smaller\n";    else if (versionCompare(version1, version2) > 0)        cout << version2 << " is smaller\n";    else        cout << "Both version are equal\n";    return 0;}
// Java program to compare two version numberimport java.util.*; class GFG {     // Method to compare two versions.    // Returns 1 if v2 is    // smaller, -1 if v1 is smaller, 0 if equal    static int versionCompare(String v1, String v2)    {        // vnum stores each numeric part of version        int vnum1 = 0, vnum2 = 0;         // loop until both String are processed        for (int i = 0, j = 0; (i < v1.length()                                || j < v2.length());) {            // Storing numeric part of            // version 1 in vnum1            while (i < v1.length()                   && v1.charAt(i) != '.') {                vnum1 = vnum1 * 10                        + (v1.charAt(i) - '0');                i++;            }             // storing numeric part            // of version 2 in vnum2            while (j < v2.length()                   && v2.charAt(j) != '.') {                vnum2 = vnum2 * 10                        + (v2.charAt(j) - '0');                j++;            }             if (vnum1 > vnum2)                return 1;            if (vnum2 > vnum1)                return -1;             // if equal, reset variables and            // go for next numeric part            vnum1 = vnum2 = 0;            i++;            j++;        }        return 0;    }     // Driver method to check above    // comparison function    public static void main(String[] args)    {        String version1 = "1.0.3";        String version2 = "1.0.7";         if (versionCompare(version1, version2) < 0)            System.out.println(version1 + " is smaller");        else if (versionCompare(version1, version2) > 0)            System.out.println(version2 + " is smaller");        else            System.out.println("Both version are equal");    }} // This code is contributed by shivanisinghss2110
# Python program to compare two version number # Method to compare two versions.# Return 1 if v2 is smaller,# -1 if v1 is smaller,,# 0 if equaldef versionCompare(v1, v2):         # This will split both the versions by '.'    arr1 = v1.split(".")    arr2 = v2.split(".")    n = len(arr1)    m = len(arr2)         # converts to integer from string    arr1 = [int(i) for i in arr1]    arr2 = [int(i) for i in arr2]      # compares which list is bigger and fills    # smaller list with zero (for unequal delimiters)    if n>m:      for i in range(m, n):         arr2.append(0)    else if m>n:      for i in range(n, m):         arr1.append(0)         # returns 1 if version 1 is bigger and -1 if    # version 2 is bigger and 0 if equal    for i in range(len(arr1)):      if arr1[i]>arr2[i]:         return 1      else if arr2[i]>arr1[i]:         return -1    return 0 # Driver program to check above comparison functionversion1 = "1.0.3"version2 = "1.0.7" ans = versionCompare(version1, version2)if ans < 0:    print (version1 + " is smaller")else if ans > 0:    print (version2 + " is smaller")else:    print ("Both versions are equal") # This code is contributed by Nikhil Kumar Singh(nickzuck_007)# and improved by Tuhin Das (tuhindas221b)
// C# program to compare// two version numberusing System;class GFG{   // Method to compare two versions.  // Returns 1 if v2 is smaller, -1  // if v1 is smaller, 0 if equal  static int versionCompare(string v1, string v2)  {    // vnum stores each numeric    // part of version    int vnum1 = 0, vnum2 = 0;     // loop until both string are    // processed    for (int i = 0, j = 0; (i < v1.Length || j < v2.Length);)    {             // storing numeric part of      // version 1 in vnum1      while (i < v1.Length && v1[i] != '.')      {        vnum1 = vnum1 * 10 + (v1[i] - '0');        i++;      }       // storing numeric part of      // version 2 in vnum2      while (j < v2.Length && v2[j] != '.')      {        vnum2 = vnum2 * 10 + (v2[j] - '0');        j++;      }       if (vnum1 > vnum2)        return 1;      if (vnum2 > vnum1)        return -1;       // if equal, reset variables and      // go for next numeric part      vnum1 = vnum2 = 0;      i++;      j++;    }    return 0;  }   // Driver code  static void Main()  {    string version1 = "1.0.3";    string version2 = "1.0.7";     if (versionCompare(version1, version2) < 0)      Console.WriteLine(version1 + " is smaller");    else if (versionCompare(version1, version2) > 0)      Console.WriteLine(version2 + " is smaller");    else      Console.WriteLine("Both version are equal");  }} // This code is contributed by divyeshrabadiya07.
<script>// Javascript implementation // Method to compare two versions.// Returns 1 if v2 is smaller, -1// if v1 is smaller, 0 if equalfunction versionCompare(v1, v2){    // vnum stores each numeric    // part of version    var vnum1 = 0, vnum2 = 0;     // loop until both string are    // processed    for (var i = 0, j = 0; (i < v1.length                            || j < v2.length);) {        // storing numeric part of        // version 1 in vnum1        while (i < v1.length && v1[i] != '.') {            vnum1 = vnum1 * 10 + (v1[i] - '0');            i++;        }         // storing numeric part of        // version 2 in vnum2        while (j < v2.length && v2[j] != '.') {            vnum2 = vnum2 * 10 + (v2[j] - '0');            j++;        }         if (vnum1 > vnum2)            return 1;        if (vnum2 > vnum1)            return -1;         // if equal, reset variables and        // go for next numeric part        vnum1 = vnum2 = 0;        i++;        j++;    }    return 0;} // Driver method to check above// comparison functionvar version1 = "1.0.3";var version2 = "1.0.7"; if (versionCompare(version1, version2) < 0)    document.write(version1 + " is smaller" + "<br>");else if (versionCompare(version1, version2) > 0)    document.write(version2 + " is smaller" + "<br>");else    document.write("Both version are equal" + "<br>"); // This is code is contributed// by shubhamsingh10</script>
Output:  
1.0.3 is greater
Complexity Analysis:  
Time Complexity: O(n), where n is the length of the string. Only one traversal of the string is needed.
Auxiliary space: O(1). As no extra space is needed.
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
tuhindas221b
shivanisinghss2110
amanverma32
andrew1234
divyeshrabadiya07
surindertarika1234
akshaysingh98088
amartyaghoshgfg
premsai96400
simmytarika5
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
KMP Algorithm for Pattern Searching
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Python program to check if a string is palindrome or not
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Check for Balanced Brackets in an expression (well-formedness) using Stack
stringstream in C++ and its applications
How to Append a Character to a String in C
Convert character array to string in C++