[Tutor] IP sorting

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Thu, 27 Dec 2001 12:25:06 -0800 (PST)

On Thu, 27 Dec 2001, Grimmtooth wrote:

> Okay, then plan 'B'.  Instead of a simple > < comparison, use a function to
> compare and have the function return a value based on a custom comparison
> where it first compares the TLD then the actual address octets.

You'll like this one: Python's sort() function works very similarly to C's
qsort() --- we can give sort() a 'comparison function' to make the sort do
things our way.

Once we have something like your compare() function:

> def compare(a,b)
>    for j in range(1,4): # assuming element 0 is the TLD and the
>                         # remainder are the octets
>      if int(a[j]) > int(b[j]:  # if we're sorting ascending, we need to swap
>        return(1)
>      elif int(a[j]) < int(b[j]:  # No need to swap, but don't continue
>        return(-1)
>    return(0)

Python can use this to do the sort: