5 ms·
it doesnt work though def swap(lst, a, b): tmp = lst[a] lst[a] = lst[b] lst[b] = tmp def optimized_sort(nu
by y4mi 5y ago
it doesnt work though
def swap(lst, a, b):
tmp = lst[a]
lst[a] = lst[b]
lst[b] = tmp
def optimized_sort(numbers):
i = 0
while i < len(numbers):
swapped = False
j = i + 1
while j < len(numbers):
if numbers[i] > numbers[j]:
swapped = True
swap(numbers, i, j)
if swapped == False:
break
j +=1
i+=1
return numbers
numbers = [1, 4,7,3,7,12,55,3,11,2,9,88,8]
optimized_sort([*numbers]) => [1, 4, 2, 7, 7, 12, 3, 3, 8, 9, 55, 11, 88]
removing the break gets you the correct order: [1, 2, 3, 3, 4, 7, 7, 8, 9, 11, 12, 55, 88]
- labawi 5y agoOriginal code would be correct, if not for a few spaces - probably a typo.
- munk-a 5y agoThis is why I like me some curly braces. (Whitespace dependent languages suck when it comes to passing around code snippets - it's just the honest truth)
- deleted 5y ago[deleted]
- maxk42 5y agoIt was just an indentation typo. Swap check should be one level higher.