Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #zigzag sort PA3#
- z = int(input()) #prompts input with z numbers#
- Z = []
- for i in range(z):
- numbers = input()
- Z.append(numbers) #stores the numbers in a list, Z#
- def printer(li, index): #printer for index in parameter list#
- for i in range(len(li)):
- if i == index:
- print(f'[{li[i]}]', end = ' ') #for printing i inside a square bracket#
- else:
- print(li[i], end = ' ')
- print()
- def zigzagzort(Z): #sorts a list in non-decreasing order#
- start = len(Z) - 1 #first round of zigzagzort goes from right to left#
- end = 0
- while True:
- printer(Z, start) #print first step#
- swapped = False
- for i in range(start-1, end-1, -1): #right to left: move the smallest element encountered so far to the end#
- if Z[i+1] < Z[i]: #check if the adjacent elements are in the wrong order#
- Z[i], Z[i+1] = Z[i+1], Z[i]
- swapped = True
- printer(Z, i) #print smallest#
- if not swapped: # we can exit the outer loop here, since no swaps means that the list is already sorted#
- break
- swapped = False
- end += 1 #we don't need to include the end element for the next rounds, already in its proper position#
- start, end = end, start # we now go through the elements from left to right#
- printer(Z, start) #print third step#
- for i in range(start, end): #left to right: move the largest element encountered so far to the end#
- if Z[i] > Z[i+1]:
- Z[i], Z[i + 1] = Z[i+1], Z[i]
- swapped = True
- printer(Z, i+1) #print largest#
- end -= 1 #again, element at the end is already at its proper position#
- start, end = end, start
- if not swapped:
- break
- zigzagzort(Z)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement