Repository navigation
Expand file tree
/
Copy pathrecursive_sorting.py
More file actions
55 lines (42 loc) · 1.52 KB
/
Copy pathrecursive_sorting.py
File metadata and controls
55 lines (42 loc) · 1.52 KB
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
### helper function
def merge( arrA, arrB ):
elements = len( arrA ) + len( arrB )
merged_arr = [0] * elements
a = 0
b = 0
# since arrA and arrB already sorted, we only need to compare the first element of each when merging!
for i in range( 0, elements ):
if a >= len(arrA): # all elements in arrA have been merged
merged_arr[i] = arrB[b]
b += 1
elif b >= len(arrB): # all elements in arrB have been merged
merged_arr[i] = arrA[a]
a += 1
elif arrA[a] < arrB[b]: # next element in arrA smaller, so add to final array
merged_arr[i] = arrA[a]
a += 1
else: # else, next element in arrB must be smaller, so add it to final array
merged_arr[i] = arrB[b]
b += 1
return merged_arr
### recursive sorting function
def merge_sort( arr ):
if len( arr ) > 1:
left = merge_sort( arr[ 0 : len( arr ) / 2 ] )
right = merge_sort( arr[ len( arr ) / 2 : ] )
arr = merge( left, right ) # merge() defined later
return arr
# STRETCH: implement an in-place merge sort algorithm
def merge_in_place(arr, start, mid, end):
# TO-DO
return arr
def merge_sort_in_place(arr, l, r):
# TO-DO
return arr
# TO-DO: implement the Quick Sort function below
def quick_sort( arr, low, high ):
return arr
# STRETCH: implement the Timsort function below
# hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt
def timsort( arr ):
return arr