Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # define a mergesort function
- def merge(list1, list2):
- list3 = []
- while len(list1) > 0 and len(list2) > 0:
- if list1[0] < list2[0]:
- list3.append(list1.pop(0))
- else:
- list3.append(list2.pop(0))
- if list1 == []:
- list3 += list2
- else:
- list3 += list1
- print("merged list is", list3)
- return list3
- def merge_sort(unsorted):
- if len(unsorted) < 2:
- return unsorted
- else:
- middle = len(unsorted) // 2
- front = unsorted[:middle]
- back = unsorted[middle:]
- print("splits are", front, back)
- front = merge_sort(front)
- back = merge_sort(back)
- return merge(front, back)
- my_list = [5,4,3,2,1]
- merge_sort(my_list)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement