Reputation:
infile = open("array.txt", "r")
array = infile.readlines()
for i in range(len(array)):
array[i] = str(array[i])
array[i] = array[i].rstrip('\n')
#insertion sort
i = 0
while i <= (len(array) - 2):
if array[i] > array[i+1]:
temp = array[i+1]
j = i
while j >= 0 and array[j] > temp:
array[j+1] = array[j]
j = j - 1
array[j+1] = temp
i = i+1
print(array)
Some numbers are sorted correctly... while some numbers are not:
original list: ['1534', '78675', '2345', '7861', '345', '8761', '1', '27456']
['1534', '2345', '78675', '7861', '345', '8761', '1', '27456']
['1534', '2345', '7861', '78675', '345', '8761', '1', '27456']
['1534', '2345', '345', '7861', '78675', '8761', '1', '27456']
['1', '1534', '2345', '345', '7861', '78675', '8761', '27456']
['1', '1534', '2345', '27456', '345', '7861', '78675', '8761']
['1', '1534', '2345', '27456', '345', '7861', '78675', '8761']
The first 2 passes worked correctly, but in the 3rd pass, '345' wasn't sorted correctly. Can anyone help me?
EDIT: If I didn't read an array from a text file, and instead just defined array, the sorting worked. Why is this so?
Upvotes: 1
Views: 216
Reputation: 76254
This is probably because "345" > "2345"
is True, because the string "345" comes lexicographically after "2345". If you want numeric sorting, try filling your original list with numbers instead of strings.
array = [1534, 78675, 2345, 7861, 345, 8761, 1, 27456]
i = 0
while i <= (len(array) - 2):
#etc
Result:
[1, 345, 1534, 2345, 7861, 8761, 27456, 78675]
Upvotes: 1