Skip to content

Instantly share code, notes, and snippets.

@liaocs2008
Created November 5, 2018 19:02
Show Gist options
  • Save liaocs2008/f5c194e7f5eb5bd0a993d8a67bfed582 to your computer and use it in GitHub Desktop.
Save liaocs2008/f5c194e7f5eb5bd0a993d8a67bfed582 to your computer and use it in GitHub Desktop.
"""
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
"""
a = [5, 1, 4, 2, 8]
length = len(a)
i = 0
while i < length:
j = 0
while j+1 < length:
if a[j] > a[j+1]:
a[j], a[j+1] = a[j+1], a[j]
j = j + 1
i = i + 1
print(a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment