Why do you think there is an error in your code? It is probably not the most elegant nor a pythonic implementation, but it seems to sort correctly.