repl.it
@tecladocode/

A level CS Book Ch.5 Pg 57 Question 1

Python

Merge Sorts

fork
loading
Files
  • main.py
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#### A level CS Book Ch.5 Pg 57 Question 1
#### Merge Sorts

import time
import random

''''''''''''''''''''''''''''''''''''''''''''''''''
#### INITIATE LIST AND FILL WITH RANDOM INTEGERS
numbers = []
length_of_list = int(input('Enter the length of the list to be sorted: '))
for x in range(length_of_list):
    numbers.append(random.randint(0,100))

print('Unsorted List: ')
print(numbers)
start = time.time()

''''''''''''''''''''''''''''''''''''''''''''''''''
#### Merge Sort Function
def merge_sort(a_list):
    if len(a_list)>1:
       midpoint = len(a_list)//2
       half1 = a_list[:midpoint]
       half2 = a_list[midpoint:]

       #recursion
       merge_sort(half1)
       merge_sort(half2)

       i=0
       j=0
       k=0

       while i < len(half1) and j < len(half2):
           if half1[i] < half2[j]:
               a_list[k]=half1[i]
               i=i+1
           else:
               a_list[k]=half2[j]
               j=j+1
           k=k+1

       while i < len(half1):
           a_list[k]=half1[i]
           i=i+1
           k=k+1

       while j < len(half2):
           a_list[k]=half2[j]
           j=j+1
           k=k+1

''''''''''''''''''''''''''''''''''''''''''''''''''

merge_sort(numbers)

print('\nSorted List: ')
print(numbers)
print('\nThis sort took', time.time() - start, 'seconds to complete.')