Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#29 Added Tree Sort #30

Merged
merged 2 commits into from
Oct 13, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
- [Counting Sort](https://github.com/Zircoz/Sorting-Algorithms-in-Python/blob/master/counting_sort.py)
- [Heap Sort](https://github.com/blackeye735/Sorting-Algorithms-in-Python/blob/master/Heapsort.py)
- [Bucket Sort](https://github.com/Zircoz/Sorting-Algorithms-in-Python/blob/master/bucket_sort.py)
- [Tree Sort](https://github.com/Zircoz/Sorting-Algorithms-in-Python/blob/master/tree_sort.py)


## Proposed List of Sorting Algos:

51 changes: 51 additions & 0 deletions tree_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
class node:
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 is None:
self.left = node(val)
else:
self.left.insert(val)
elif val > self.val:
if self.right is None:
self.right = node(val)
else:
self.right.insert(val)
else:
self.val = val


def inorder(root, res):
if root:
inorder(root.left, res)
res.append(root.val)
inorder(root.right, res)


def tree_sort(arr):
if len(arr) == 0:
return arr
root = node(arr[0])
for i in range(1, len(arr)):
root.insert(arr[i])
res = []
inorder(root, res)
return res

def printList(arr):
for i in range(len(arr)):
print(arr[i],end=" ")
print()

# driver code to test the above code
arr = [1, 12, 11, 2, 13, 5, 6, 7]
print ("Given array is", end="\n")
printList(arr)
tree_sort(arr)
print("Sorted array is: ", end="\n")
printList(arr)