LordNoob LordNoob - 1 year ago 77
Python Question

Why doesn't my alphabetical sorting algorithm work?

I made this algorithm in Python to sort a list of names alphabetically and I can't figure out why it doesn't work properly when given this list:

for a in range(0,len(V)):
for b in range(a,len(V)):
for N in range(0,min(len(V[a]),len(V[b]))):
if ord(V[b][N])<ord(V[a][N]):
if equal==True and len(V[a])>len(V[b]):

Answer Source

Ah, I found the problem. Try dry running your code on these two examples:

V = ["ABCZ", "XYZA"]
V = ["ABCE", "XYZF"]

For the first example, your if condition isn't triggered until the last characters, 'Z'(from "ABCZ") and 'A'(from "XYZA") are compared.

if ord(V[b][N])<ord(V[a][N]):

This wrongly swaps the two strings.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download