Skip to content
Open
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
43 changes: 43 additions & 0 deletions Heapsort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#python heap Sort

#function of heapify
#n=size of heap
def heapify(arr, n, i):
largest = i #initialize the largest as the root
l = 2 * i + 1#check child of left = 2*i + 1
r = 2 * i + 2#check child of right = 2*i + 2

#if left child of root exists and > than root
if l < n and arr[largest] < arr[l]:
largest = l

#if right child of root exists and > than root
if r < n and arr[largest] < arr[r]:
largest = r

#changing the root to largest
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
#heapify the root.
heapify(arr, n, largest)

#function heapsort to sort
def heapSort(arr):
n = len(arr)

#build the maxheap.
for i in range(n//2 - 1, -1, -1):
heapify(arr, n, i)

#extracting the elements
for i in range(n-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i]
heapify(arr, i, 0)


#---main program--
arr = [12, 11, 13, 5, 6, 7]
print("Array we entering: ",arr)
heapSort(arr)
print()
print("Sorted array is",arr)
47 changes: 47 additions & 0 deletions QuickSort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#quick sort algorithm

arr=[]
n=int(input("Enter the array size: "))
def userinputs(arr):
for i in range(n):
v= int((input("Enter a number: ")))#add the elements to the array
arr.append(v)

def partition(arr,start,end):
i=(start-1)#getting the index of the smallest element
pivot=arr[end] #get an elemt to check

for j in range(start,end):
if(arr[j]<=pivot): #if current element <=pivot
i=i+1 #increment the index of smallest element
arr[i],arr[j]=arr[j],arr[i] #swap the elements
#exchanging
arr[i+1],arr[end]=arr[end],arr[i+1]
return(i+1)

def quickSort(arr,start,end):
if (start<end):
#partition index q
q=partition(arr,start,end)
#sorting the elements left & right partition
quickSort(arr,start,q-1) #left partition
quickSort(arr,q+1,end)#right partition



#----main prog---

#calling quick sort

userinputs(arr)
print("entered arraylist")
print(arr)

partition(arr,0,n-1)
print("partitioned arraylist")
print(arr)

quickSort(arr,0,n-1)

print("sorted arraylist")
print(arr)