I am trying to make a basic bubble sort and count the number of passes and swaps it takes to complete.
So for the example input:
23
- This is just the amount of numbers below.. Don't ask why I can't just use the len()
20 18 8 11 17 12 13 21 10 14 9 5 19 6 16 7 2 15 1 3 22 4 23
def bubbleSort(amount, numbers):
sorted = False
swapCount, passCount = 0,0
while not sorted:
sorted = True
for i in range(amount-1):
if numbers[i] > numbers[i+1]:
sorted = False
swapCount += 1
numbers[i], numbers[i+1] = numbers[i+1], numbers[i]
passCount += 1
print(numbers)
print('%s %s') % (passCount, swapCount)
bubbleSort(input(),raw_input().split())
Naturally, the expected output would be:
19 passes, 151 swaps, and the list in correct order least to greatest. However, I keep ending up with 19 passes and 109 swaps and my order looking like this:
['1', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '2', '20', '21', '22', '23', '3', '4', '5', '6', '7', '8', '9']
Can anyone steer me in the right direction as to how I can sort things properly and 2
isn't considered greater than 10
?
The result of raw_input().split()
is a list of strings, not integers. Your algorithm is correct -- you're sorting the strings in alphabetical order.
A quick fix is to use e.g.
bubbleSort(input(), [int(x) for x in raw_input().split()])