Advertisement
Rararain

Untitled

Jan 29th, 2020
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. #zigzag sort PA3#
  2. z = int(input()) #prompts input with z numbers#
  3. Z = []
  4. for i in range(z):
  5. numbers = input()
  6. Z.append(numbers) #stores the numbers in a list, Z#
  7.  
  8. def printer(li, index): #printer for index in parameter list#
  9. for i in range(len(li)):
  10. if i == index:
  11. print(f'[{li[i]}]', end = ' ') #for printing i inside a square bracket#
  12. else:
  13. print(li[i], end = ' ')
  14. print()
  15.  
  16. def zigzagzort(Z): #sorts a list in non-decreasing order#
  17. start = len(Z) - 1 #first round of zigzagzort goes from right to left#
  18. end = 0
  19. while True:
  20. printer(Z, start) #print first step#
  21. swapped = False
  22. for i in range(start-1, end-1, -1): #right to left: move the smallest element encountered so far to the end#
  23. if Z[i+1] < Z[i]: #check if the adjacent elements are in the wrong order#
  24. Z[i], Z[i+1] = Z[i+1], Z[i]
  25. swapped = True
  26. printer(Z, i) #print smallest#
  27. if not swapped: # we can exit the outer loop here, since no swaps means that the list is already sorted#
  28. break
  29. swapped = False
  30. end += 1 #we don't need to include the end element for the next rounds, already in its proper position#
  31. start, end = end, start # we now go through the elements from left to right#
  32. printer(Z, start) #print third step#
  33. for i in range(start, end): #left to right: move the largest element encountered so far to the end#
  34. if Z[i] > Z[i+1]:
  35. Z[i], Z[i + 1] = Z[i+1], Z[i]
  36. swapped = True
  37. printer(Z, i+1) #print largest#
  38. end -= 1 #again, element at the end is already at its proper position#
  39. start, end = end, start
  40. if not swapped:
  41. break
  42.  
  43. zigzagzort(Z)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement