Python: Using binary search to perform natural sorting

77 Views Asked by At

I am using a binary search to insert into a sorted list of lists. The code below works fine for an alphanumeric sort but I cannot figure out how to make the sort work in a natural sorting order.

The key "name" will contain a mixture of numerical values and Words and currently sorts alphabetically resulting in the numbers being in string rather than numeric order.

Is it possible to insert into a list of lists in natural order?

For example if I want to insert the following lists

{ "Orange", "Frog" 3, 4, 55}
{ 3031, "Bob", 21, 4, 56 }
{ 400, "Tree", 6, 66, 75}

I would like the order to end up as

{ 400, "Tree", 6, 66, 75}
{ 3031, "Bob", 21, 4, 56 }
{ "Orange", "Frog", 3, 4, 55}

My code is as follows:

def binSearch(listSearch, name):
low = 0  
high = len(listSearch) 
mid = 0

while low < high:  
    # for get integer result   
    mid = (high + low) // 2  

    # Check if name is present at mid   
    if listSearch[mid].name < name:
        low = mid + 1 
    else:
        high=mid

This results in

{ 3031, "Bob", 21, 4, 56 }
{ 400, "Tree", 6, 66, 75}
{ "Orange", "Frog", 3, 4, 55 }
0

There are 0 best solutions below