-
Notifications
You must be signed in to change notification settings - Fork 1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #119 from nickcodhackder/master
Created heapsort.py
- Loading branch information
Showing
2 changed files
with
66 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
def heapify(arr, n, i): | ||
largest = i # Initialize largest as root | ||
l = 2 * i + 1 # left = 2*i + 1 | ||
r = 2 * i + 2 # right = 2*i + 2 | ||
if l < n and arr[i] < arr[l]: | ||
largest = l | ||
if r < n and arr[largest] < arr[r]: | ||
largest = r | ||
if largest != i: | ||
arr[i],arr[largest] = arr[largest],arr[i] # swap | ||
heapify(arr, n, largest) | ||
def heapSort(arr): | ||
n = len(arr) | ||
for i in range(n, -1, -1): | ||
heapify(arr, n, i) | ||
for i in range(n-1, 0, -1): | ||
arr[i], arr[0] = arr[0], arr[i] # swap | ||
heapify(arr, i, 0) | ||
|
||
# Driver code to test above | ||
arr = [ 12, 11, 13, 5, 6, 7] | ||
heapSort(arr) | ||
n = len(arr) | ||
print ("Sorted array is") | ||
for i in range(n): | ||
print ("%d" %arr[i]), |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
class Node: | ||
def __init__(self, data): | ||
self.data = data | ||
self.next = None | ||
|
||
class LinkedList: | ||
def __init__(self): | ||
self.head = None | ||
def reverse(self): | ||
prev = None | ||
current = self.head | ||
while(current is not None): | ||
next = current.next | ||
current.next = prev | ||
prev = current | ||
current = next | ||
self.head = prev | ||
def push(self, new_data): | ||
new_node = Node(new_data) | ||
new_node.next = self.head | ||
self.head = new_node | ||
def printList(self): | ||
temp = self.head | ||
while(temp): | ||
print temp.data, | ||
temp = temp.next | ||
|
||
|
||
# Driver program to test above functions | ||
llist = LinkedList() | ||
llist.push(20) | ||
llist.push(4) | ||
llist.push(15) | ||
llist.push(85) | ||
|
||
print "Given Linked List" | ||
llist.printList() | ||
llist.reverse() | ||
print "\nReversed Linked List" | ||
llist.printList() |