mirror of
https://hub.njuu.cf/TheAlgorithms/Python.git
synced 2023-10-11 13:06:12 +08:00
Add sorts for python3
This commit is contained in:
parent
7dcbca516f
commit
744dd71238
16
sorts/pancake_sort.py
Normal file
16
sorts/pancake_sort.py
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
# Pancake sort algorithm
|
||||||
|
# Only can reverse array from 0 to i
|
||||||
|
|
||||||
|
def pancakesort(arr):
|
||||||
|
cur = len(arr)
|
||||||
|
while cur > 1:
|
||||||
|
# Find the maximum number in arr
|
||||||
|
mi = arr.index(max(arr[0:cur]))
|
||||||
|
# Reverse from 0 to mi
|
||||||
|
arr = arr[mi::-1] + arr[mi+1:len(arr)]
|
||||||
|
# Reverse whole list
|
||||||
|
arr = arr[cur-1::-1] + arr[cur:len(arr)]
|
||||||
|
cur -= 1
|
||||||
|
return arr
|
||||||
|
|
||||||
|
print(pancakesort([0,10,15,3,2,9,14,13]))
|
45
sorts/tree_sort.py
Normal file
45
sorts/tree_sort.py
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
# Tree_sort algorithm
|
||||||
|
# Build a BST and in order traverse.
|
||||||
|
|
||||||
|
class node():
|
||||||
|
# BST data structure
|
||||||
|
def __init__(self, val):
|
||||||
|
self.val = val
|
||||||
|
self.left = None
|
||||||
|
self.right = None
|
||||||
|
|
||||||
|
def insert(self,val):
|
||||||
|
if self.val:
|
||||||
|
if val < self.val:
|
||||||
|
if self.left == None:
|
||||||
|
self.left = node(val)
|
||||||
|
else:
|
||||||
|
self.left.insert(val)
|
||||||
|
elif val > self.val:
|
||||||
|
if self.right == None:
|
||||||
|
self.right = node(val)
|
||||||
|
else:
|
||||||
|
self.right.insert(val)
|
||||||
|
else:
|
||||||
|
self.val = val
|
||||||
|
|
||||||
|
def inorder(root, res):
|
||||||
|
# Recursive travesal
|
||||||
|
if root:
|
||||||
|
inorder(root.left,res)
|
||||||
|
res.append(root.val)
|
||||||
|
inorder(root.right,res)
|
||||||
|
|
||||||
|
def treesort(arr):
|
||||||
|
# Build BST
|
||||||
|
if len(arr) == 0:
|
||||||
|
return arr
|
||||||
|
root = node(arr[0])
|
||||||
|
for i in range(1,len(arr)):
|
||||||
|
root.insert(arr[i])
|
||||||
|
# Traverse BST in order.
|
||||||
|
res = []
|
||||||
|
inorder(root,res)
|
||||||
|
return res
|
||||||
|
|
||||||
|
print(treesort([10,1,3,2,9,14,13]))
|
Loading…
x
Reference in New Issue
Block a user