I want to Bubblesort a file by numbers and I have propably 2 mistakes in my code.
The lines of the file contain: string-space-number
The response is a wrong sorting or sometimes I got also an IndexError because x.append(row[l]) is out of range
Hope someone can help me
Code:
#!/usr/bin/python
filename = "Numberfile.txt"
fo = open(filename, "r")
x, y, z, b = [], [], [], []
for line in fo: # read
row = line.split(" ") # split items by space
x.append(row[1]) # number
liste = fo.readlines()
lines = len(liste)
fo.close()
for passesLeft in range(lines-1, 0, -1):
for i in range(passesLeft):
if x[i] > x[i+1]:
temp = liste[i]
liste[i] = liste[i+1]
liste[i+1] = temp
fo = open(filename, "w")
for i in liste:
fo.writelines("%s" % i)
fo.close()