Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from random import randrange
- arr = [1]
- def generate_random():
- for i in range(0,20):
- arr.append(randrange(0,20))
- def shift(s, e):
- end = arr[e]
- for i in range(e-1, s-1, -1):
- arr[i+1] = arr[i]
- arr[s] = end
- # def while_shift():
- # value = arr[start2]
- # index = start2
- # # Shift all the elements between element 1
- # # element 2, right by 1.
- # while (index != start):
- # arr[index] = arr[index - 1]
- # index -= 1
- # arr[start] = value
- def merge(p1, p2, end):
- print("Pointer 1: " + str(p1) + ", Pointer 2 " + str(p2))
- # If the direct merge is already sorted (already sorted in the previous stack)
- if (arr[p2-1] <= arr[p2]):
- return
- # Two pointers to maintain start
- # of both arrays to merge
- while (p1 <= p2-1 and p2 <= end):
- # If element 1 is in right place
- if (arr[p1] <= arr[p2]):
- p1 += 1
- else:
- shift(p1, p2)
- # Update all the pointers
- p1 += 1
- p2 += 1
- def merge_sort(s, e):
- if s < e:
- m = (e - s) // 2 + s
- # first half (s,m)
- merge_sort(s,m)
- # second half (m+1,e)
- merge_sort(m+1,e)
- merge(s,m+1,e)
- def main():
- generate_random()
- print(arr)
- if len(arr) >= 1:
- merge_sort(0,len(arr)-1)
- print(arr)
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement