Compare two version numbers of a software

Given two versions of a software, write an algorithm to find out which version is the latest.

Example:

Version A: 1.1.0 Version B: 1.1.1
Given version B latest than version A

Version A: 1.2.1 Version B: 1.2.1
Given versions are the same

Version A: 2.2.0 Version B: 2.2
Given versions are the same

Version A: 2.2.0.0.1 Version B: 2.2.0
Given version A latest than version B

Version A: 2.2.0.0.1 Version B: 2.2.1
Given version B latest than version A

Approach: 

Split the versions by ‘.’ and store it in an array. Call the arrays, versions_a[] and versions_b[]. Now iterate both the arrays at the same time and compare the version number from both arrays. During iteration, if at any point if one version number is greater than another we have found which version is the latest, return that. If any of the arrays gets over before another array then traverse the array which is remaining and look for any number greater than 0, if yes then the longer version is the latest one else both versions are the same.

Complete Code:

Output:

Version A: 1.1.0 Version B: 1.1.1
Given version B latest than version A
--------------------------------------------------
Version A: 1.2.1 Version B: 1.2.1
Given versions are the same
--------------------------------------------------
Version A: 2.2.0 Version B: 2.2
Given versions are the same
--------------------------------------------------
Version A: 2.2.0.0.1 Version B: 2.2.0
Given version A latest than version B
--------------------------------------------------
Version A: 2.2.0.0.1 Version B: 2.2.1
Given version B latest than version A
--------------------------------------------------
Version A: a.b.c Version B: 2.2.1
Given versions are not valid
--------------------------------------------------
Version A: 1.  2.3 Version B: 2.2.1
Given version B latest than version A
------------------------------------------------

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.