Sort the given IP addresses in ascending order

Given an array arr[] of IP Addresses where each element is a IPv4 Address, the task is to sort the given IP addresses in increasing order.
Examples:

Input: arr[] = {‘126.255.255.255’, ‘169.255.0.0’, ‘169.253.255.255’}
Output: ‘126.255.255.255’, ‘169.253.255.255’, ‘169.255.0.0’
Explanation:
As the second octet of the third IP Address is less than the second IP Address whereas the first octet is same. Due to which the third IP Address will be smaller than the Third IP Address.
169.255.0.0 > 169.253.255.255

Input: arr[] = {‘192.168.0.1’, ‘192.168.1.210’, ‘192.168.0.227’}
Output: ‘192.168.0.1’, ‘192.168.0.227’, ‘192.168.1.210’

Approach: The idea is to use a custom comparator to sort the given IP addresses. Since IPv4 has 4 octets, we will compare the addresses octet by octet.

• Check the first octet of the IP Address, If the first address has a greater first octet, then return True to swap the IP address, otherwise, return False.
• If the first octet of the IP Addresses is same then compare the second octet of both IP Address. If the first address has a greater second octet, then return True to swap the IP address, otherwise, return False.
• If the second octet of the IP Addresses is also the same, then compare the third octet of both IP Address. If the first address has a greater third octet, then return True to swap the IP address, otherwise, return False.
• If the third octet of the IP Addresses is also the same, then compare the fourth octet of both IP Address. If the first address has a greater third octet, then return True to swap the IP address, otherwise, return False.
• If the fourth octet is also the same, then both IP Address is equal. Then also return False.

Below is the implementation of the above approach:

Java

 `import` `java.util.Arrays;``import` `java.util.Comparator;` `public` `class` `GFG {``    ``// Custom Comparator to sort the Array in the increasing order``    ``static` `class` `CustomComparator ``implements` `Comparator {``        ``@Override``        ``public` `int` `compare(String a, String b) {``            ``// Breaking into the octets``            ``String[] octetsA = a.trim().split(``"\\."``);``            ``String[] octetsB = b.trim().split(``"\\."``);` `            ``// Condition if the IP Address is same then return 0``            ``if` `(Arrays.equals(octetsA, octetsB)) {``                ``return` `0``;``            ``} ``else` `if` `(Integer.parseInt(octetsA[``0``]) > Integer.parseInt(octetsB[``0``])) {``                ``return` `1``;``            ``} ``else` `if` `(Integer.parseInt(octetsA[``0``]) < Integer.parseInt(octetsB[``0``])) {``                ``return` `-``1``;``            ``} ``else` `if` `(Integer.parseInt(octetsA[``1``]) > Integer.parseInt(octetsB[``1``])) {``                ``return` `1``;``            ``} ``else` `if` `(Integer.parseInt(octetsA[``1``]) < Integer.parseInt(octetsB[``1``])) {``                ``return` `-``1``;``            ``} ``else` `if` `(Integer.parseInt(octetsA[``2``]) > Integer.parseInt(octetsB[``2``])) {``                ``return` `1``;``            ``} ``else` `if` `(Integer.parseInt(octetsA[``2``]) < Integer.parseInt(octetsB[``2``])) {``                ``return` `-``1``;``            ``} ``else` `if` `(Integer.parseInt(octetsA[``3``]) > Integer.parseInt(octetsB[``3``])) {``                ``return` `1``;``            ``} ``else` `{``                ``return` `-``1``;``            ``}``        ``}``    ``}` `    ``// Function to sort the IP Addresses``    ``public` `static` `void` `sortIPAddress(String[] arr) {``        ``// Sort the Array using Custom Comparator``        ``Arrays.sort(arr, ``new` `CustomComparator());` `        ``System.out.println(String.join(``" "``, arr));``    ``}` `    ``// Driver Code``    ``public` `static` `void` `main(String[] args) {``        ``String[] arr = {``"192.168.0.1"``, ``"192.168.1.210"``, ``"192.168.0.227"``};` `        ``// Function Call``        ``sortIPAddress(arr);``    ``}``}` `//contributed by Aditya Sharma`

Python

 `# Python implementation to sort``# the array of the IP Address` `from` `functools ``import` `cmp_to_key` `# Custom Comparator to sort the``# Array in the increasing order``def` `customComparator(a, b):``    ` `    ``# Breaking into the octets ``    ``octetsA ``=` `a.strip().split(``"."``)``    ``octetsB ``=` `b.strip().split(``"."``)``    ` `    ``# Condition if the IP Address``    ``# is same then return 0``    ``if` `octetsA ``=``=` `octetsB:``        ``return` `0``    ``elif` `octetsA[``0``] > octetsB[``0``]:``        ``return` `1``    ``elif` `octetsA[``0``] < octetsB[``0``]:``        ``return` `-``1``    ``elif` `octetsA[``1``] > octetsB[``1``]:``        ``return` `1``    ``elif` `octetsA[``1``] < octetsB[``1``]:``        ``return` `-``1``    ``elif` `octetsA[``2``] > octetsB[``2``]:``        ``return` `1``    ``elif` `octetsA[``2``] < octetsB[``2``]:``        ``return` `-``1``    ``elif` `octetsA[``3``] > octetsB[``3``]:``        ``return` `1``    ``elif` `octetsA[``3``] < octetsB[``3``]:``        ``return` `-``1` `# Function to sort the IP Addresses``def` `sortIPAddress(arr):``    ` `    ``# Sort the Array using ``    ``# Custom Comparator``    ``arr ``=` `sorted``(arr, key ``=` `\``       ``cmp_to_key(customComparator))``       ` `    ``print``(``*``arr)``    ``return` `arr``    ` `# Driver Code``if` `__name__ ``=``=` `"__main__"``:``    ``arr ``=` `[``'192.168.0.1'``, ``           ``'192.168.1.210'``, ``           ``'192.168.0.227'``]``    ` `    ``# Function Call``    ``sortIPAddress(arr)`

C#

 `using` `System;``using` `System.Linq;` `public` `class` `SortIPAddress``{``    ``// Custom Comparator to sort the Array in the increasing order``    ``public` `static` `int` `CustomComparator(``string` `a, ``string` `b)``    ``{``        ``// Breaking into the octets``        ``string``[] octetsA = a.Trim().Split(``'.'``);``        ``string``[] octetsB = b.Trim().Split(``'.'``);` `        ``// Condition if the IP Address is same then return 0``        ``if` `(Enumerable.SequenceEqual(octetsA, octetsB))``        ``{``            ``return` `0;``        ``}``        ``else` `if` `(Int32.Parse(octetsA[0]) > Int32.Parse(octetsB[0]))``        ``{``            ``return` `1;``        ``}``        ``else` `if` `(Int32.Parse(octetsA[0]) < Int32.Parse(octetsB[0]))``        ``{``            ``return` `-1;``        ``}``        ``else` `if` `(Int32.Parse(octetsA[1]) > Int32.Parse(octetsB[1]))``        ``{``            ``return` `1;``        ``}``        ``else` `if` `(Int32.Parse(octetsA[1]) < Int32.Parse(octetsB[1]))``        ``{``            ``return` `-1;``        ``}``        ``else` `if` `(Int32.Parse(octetsA[2]) > Int32.Parse(octetsB[2]))``        ``{``            ``return` `1;``        ``}``        ``else` `if` `(Int32.Parse(octetsA[2]) < Int32.Parse(octetsB[2]))``        ``{``            ``return` `-1;``        ``}``        ``else` `if` `(Int32.Parse(octetsA[3]) > Int32.Parse(octetsB[3]))``        ``{``            ``return` `1;``        ``}``        ``else``        ``{``            ``return` `-1;``        ``}``    ``}` `    ``// Function to sort the IP Addresses``    ``public` `static` `void` `sortIPAddress(``string``[] arr)``    ``{``        ``// Sort the Array using Custom Comparator``        ``Array.Sort(arr, CustomComparator);` `        ``Console.WriteLine(``string``.Join(``" "``, arr));``    ``}` `    ``// Driver Code``    ``public` `static` `void` `Main(``string``[] args)``    ``{``        ``string``[] arr = {``"192.168.0.1"``, ``"192.168.1.210"``, ``"192.168.0.227"``};` `        ``// Function Call``        ``sortIPAddress(arr);``    ``}``}` `//contributed by Aditya Sharma`

Javascript

 ``

C++

 `// C++ code for the above approach` `#include ``#include ``#include ``#include ` `using` `namespace` `std;` `// Custom Comparator to sort the array in increasing order``bool` `customComparator(string a, string b) {``    ``// Breaking into the octets``    ``vector octetsA;``    ``vector octetsB;` `    ``string octet = ``""``;``    ``for` `(``int` `i = 0; i < a.size(); i++) {``        ``if` `(a[i] == ``'.'``) {``            ``octetsA.push_back(octet);``            ``octet = ``""``;``        ``} ``else` `{``            ``octet += a[i];``        ``}``    ``}``    ``octetsA.push_back(octet);` `    ``octet = ``""``;``    ``for` `(``int` `i = 0; i < b.size(); i++) {``        ``if` `(b[i] == ``'.'``) {``            ``octetsB.push_back(octet);``            ``octet = ``""``;``        ``} ``else` `{``            ``octet += b[i];``        ``}``    ``}``    ``octetsB.push_back(octet);` `    ``// Condition if the IP Address is same then return false``    ``if` `(octetsA == octetsB) {``        ``return` `false``;``    ``}` `    ``// Compare the octets and return the result``    ``for` `(``int` `i = 0; i < 4; i++) {``        ``if` `(stoi(octetsA[i]) > stoi(octetsB[i])) {``            ``return` `false``;``        ``} ``else` `if` `(stoi(octetsA[i]) < stoi(octetsB[i])) {``            ``return` `true``;``        ``}``    ``}``    ``return` `false``;``}` `// Function to sort the IP Addresses``vector sortIPAddress(vector arr) {``    ``// Sort the Array using Custom Comparator``    ``sort(arr.begin(), arr.end(), customComparator);``    ``return` `arr;``}` `// Driver Code``int` `main() {``    ``vector arr = {``"192.168.0.1"``, ``"192.168.1.210"``, ``"192.168.0.227"``};` `    ``// Function Call``    ``arr = sortIPAddress(arr);` `    ``// Print the sorted array``    ``for` `(``int` `i = 0; i < arr.size(); i++) {``        ``cout << arr[i] << ``" "``;``    ``}``    ``cout << endl;` `    ``return` `0;``}` `// This code is contributed by princekumaras`

Output:
```192.168.0.1
192.168.0.227
192.168.1.210```

Time Complexity: O(N*logN)

Space Complexity: O(N) as octetsA, octetsB vectors has been created.

Previous
Next