Skip to content

Commit 6fa7e44

Browse files
authored
Merge pull request TheAlgorithms#259 from pl04351820/master
Add sorts for python3
2 parents 7dcbca5 + 744dd71 commit 6fa7e44

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

sorts/pancake_sort.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# Pancake sort algorithm
2+
# Only can reverse array from 0 to i
3+
4+
def pancakesort(arr):
5+
cur = len(arr)
6+
while cur > 1:
7+
# Find the maximum number in arr
8+
mi = arr.index(max(arr[0:cur]))
9+
# Reverse from 0 to mi
10+
arr = arr[mi::-1] + arr[mi+1:len(arr)]
11+
# Reverse whole list
12+
arr = arr[cur-1::-1] + arr[cur:len(arr)]
13+
cur -= 1
14+
return arr
15+
16+
print(pancakesort([0,10,15,3,2,9,14,13]))

sorts/tree_sort.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# Tree_sort algorithm
2+
# Build a BST and in order traverse.
3+
4+
class node():
5+
# BST data structure
6+
def __init__(self, val):
7+
self.val = val
8+
self.left = None
9+
self.right = None
10+
11+
def insert(self,val):
12+
if self.val:
13+
if val < self.val:
14+
if self.left == None:
15+
self.left = node(val)
16+
else:
17+
self.left.insert(val)
18+
elif val > self.val:
19+
if self.right == None:
20+
self.right = node(val)
21+
else:
22+
self.right.insert(val)
23+
else:
24+
self.val = val
25+
26+
def inorder(root, res):
27+
# Recursive travesal
28+
if root:
29+
inorder(root.left,res)
30+
res.append(root.val)
31+
inorder(root.right,res)
32+
33+
def treesort(arr):
34+
# Build BST
35+
if len(arr) == 0:
36+
return arr
37+
root = node(arr[0])
38+
for i in range(1,len(arr)):
39+
root.insert(arr[i])
40+
# Traverse BST in order.
41+
res = []
42+
inorder(root,res)
43+
return res
44+
45+
print(treesort([10,1,3,2,9,14,13]))

0 commit comments

Comments
 (0)