Repository navigation
Expand file tree
/
Copy pathsort.py
More file actions
112 lines (90 loc) · 2.59 KB
/
Copy pathsort.py
File metadata and controls
112 lines (90 loc) · 2.59 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# TO-DO: Complete the selection_sort() function below
arr = [5, 4, 8, 3, 1, 7, 9, 1]
print('arr in:', arr)
# Finds smallest then 2nd smallest and so on
def selection_sort(arr):
for i in range(len(arr) - 1):
cur_index = i
smallest_index = cur_index
for j in range(i, len(arr)):
if arr[smallest_index] > arr[j]:
smallest_index = j
arr[i], arr[smallest_index] = arr[smallest_index], arr[i]
print('arr out:', arr)
return arr
# selection_sort(arr)
def selection_sort2(arr):
# 1 - loop one
for i in range(len(arr) - 1):
lowNum = i
# 2 - 2nd loop
for x in range(i, len(arr)):
# find lowest
if arr[lowNum] > arr[x]:
arr[i], arr[lowNum] = arr[lowNum], arr[i]
print('arr2 out:', arr)
return arr
# selection_sort2(arr)
# Compares 1st to 2nd, 2nd to third and so on
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for x in range(n-i-1):
if arr[x] > arr[x+1]:
arr[x], arr[x + 1] = arr[x + 1], arr[x]
# print('bubble arr:', arr)
return arr
# bubble_sort(arr)
def bubbleSort(arr):
n = len(arr)
for i in range(n):
for x in range(n-i-1):
if arr[x] > arr[x+1]:
arr[x], arr[x+1] = arr[x+1], arr[x]
print('arrbubble', arr)
return arr
# bubbleSort(arr)
def oneAtATime(arr):
x = len(arr)
for i in range(x):
for z in range(x-i-1):
if arr[z] > arr[z+1]:
arr[z], arr[z+1] = arr[z+1], arr[z]
print('1atatime', arr)
return arr
# oneAtATime(arr)
arrA = [1, 2, 3]
arrB = [4, 5, 6]
def merge(arrA, arrB):
elements = len(arrA) + len(arrB)
# print('elements:', elements)
merged_arr = [0] * elements
# UPER
# U - UNDERSTAND
# TAKE 2 ORDERED LISTS AND MERGE THEM TOGETHER
# P - PLAN
# FOR EACH ITEM
for i in arrA:
# print('i:', i)
merged_arr[i-1] = i
for x in arrB:
# print('x', x)
merged_arr[x - 1] = x
print('merged_arr:', merged_arr)
merged_arr.remove(1)
return merged_arr
merge(arrA, arrB)
arr = [1, 5, 8, 4, 2, 9, 6, 0, 3, 7]
# TO-DO: implement the Merge Sort function below USING RECURSION -- broken
# def merge_sort( arr ):
# if len(arr) > 1:
# middle = len(arr) // 2
# first_half = arr[0:middle]
# second_half = arr[middle:]
# left = merge_sort(first_half)
# right = merge_sort(second_half)
# arr = merge(left, right)
# print('merged sorted', arr)
# return arr
#
# merge_sort(arr)