Advertisement
ihor_ks

wave_list.py

Nov 6th, 2018
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.20 KB | None | 0 0
  1. #!/usr/bin/python3
  2.  
  3. import random
  4.  
  5. # The program sorts the list of numbers in the form of waves.
  6. # It means a list for which the following condition
  7. # is true a1> = a2 <= a3> = a4 <= ...
  8.  
  9. def merge_sort(l):
  10.     """Recursive merge sort."""
  11.     if len(l) > 1:
  12.         mid = len(l) // 2
  13.         left = l[:mid]
  14.         right = l[mid:]
  15.        
  16.         merge_sort(left)
  17.         merge_sort(right)
  18.  
  19.         i = j = k = 0
  20.         while i < len(left) and j < len(right):
  21.             if left[i] < right[j]:
  22.                 l[k] = left[i]
  23.                 i += 1
  24.             else:
  25.                 l[k] = right[j]
  26.                 j += 1
  27.             k += 1
  28.        
  29.         if i < len(left):
  30.             l[k: k + len(left[i:])] = left[i:]
  31.         if j < len(right):
  32.             l[k: k + len(right[j:])] = right[j:]       
  33.                
  34. n = int(input('Enter the length of the list (positive integer):\n >'))
  35. lst = random.sample(range(n * 10), n)
  36. print("Input list: {}".format(lst))
  37.  
  38. merge_sort(lst)
  39.  
  40. arr = []
  41. i = 0
  42. tmp = 0
  43.  
  44. while i != n - 1:
  45.     if i % 2 == 0:
  46.         tmp = lst[i]
  47.         arr.append(lst[i+1])
  48.     else:
  49.         arr.append(tmp)
  50.     i += 1          
  51.      
  52. print("Output list: ", arr)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement