![]() |
VOOZH | about |
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.255Input: 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.
Below is the implementation of the above approach:
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.