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.


Input: arr[] = {‘’, ‘’, ‘’}
Output: ‘’, ‘’, ‘’
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. >

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

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

Below is the implementation of the above approach:





# 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 sortIPAdddress(arr):
    # Sort the Array using 
    # Custom Comparator
    arr = sorted(arr, key = \
    return arr
# Driver Code
if __name__ == "__main__":
    arr = [''
    # Function Call


Time Complexity: O(N*logN)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :