In: Computer Science
(Using C++)
Sample array: 100, 45, 33, 55, 356, 11, 1000, 999, 987
You need to perform the following steps to evaluate the algorithm’s time complexity:
You need to recommend the sorting algorithm that should be used for sorting based on its execution time.
Note that you can use any programming language to implement the steps above.
Your program should contain the following:
Your program should also do the following:
Algorithms :
1. Heap Sort
2. Quick Sort
import timeit
#Heapsort implementation
def heapify(arr, n, i):
largest = i
l = 2 * i + 1
r = 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]
heapify(arr, n, largest)
def heapSort(arr):
n = len(arr)
for i in range(n//2 - 1, -1, -1):
heapify(arr, n, i)
for i in range(n-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i]
heapify(arr, i, 0)
return arr
#quicksort Implementatio
def partition(arr,low,high):
i = ( low-1 )
pivot = arr[high]
for j in range(low , high):
if arr[j] < pivot:
i = i+1
arr[i],arr[j] = arr[j],arr[i]
arr[i+1],arr[high] = arr[high],arr[i+1]
return ( i+1 )
def quickSort(arr,low,high):
if low < high:
pi = partition(arr,low,high)
quickSort(arr, low, pi-1)
quickSort(arr, pi+1, high)
return arr
data = [100, 45, 33, 55, 356, 11, 1000, 999, 987]
startHeapSort = timeit.timeit()
sortHeap = heapSort(data.copy())
endHeapSort = timeit.timeit()
startQuickSort = timeit.timeit()
sortQuick = quickSort(data.copy(), 0, len(data.copy())-1)
endQuickSort = timeit.timeit()
tHeapSort = endHeapSort - startHeapSort
tQuickSort = endQuickSort - startQuickSort
if tHeapSort < tQuickSort:
print("Heap Sort execution time is better.")
else:
print("Quick Sort execution time is better.")