Aoa Lab02 23102B2007
Aoa Lab02 23102B2007
Experiment 2
Number
Experiment Analysis of Runtime for Quick Sort
Title
Resources /
Apparatus
Hardware: Desktop/Laptop Software: VS Code
Required
Description This Python program compares the runtime performance of the Quick Sort
algorithm for sorting randomly arranged and sorted arrays of varying sizes. It
generates arrays ranging from 5000 to 50000 elements, applies Quick Sort to
each array, measures the runtime of the sorting process, and plots the runtime
on a graph. The graph provides visual insights into Quick Sort's efficiency and
scalability as the input size increases, helping to assess its performance
characteristics.
def generate_random_array(size):
return [random.randint(1, 1000) for _ in range(size)]
def generate_sorted_array(size):
Department of Computer Engineering
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
def measure_quick_sort_runtime(array):
start_time = time.time()
quick_sort(array)
end_time = time.time()
return end_time - start_time
random_runtimes = []
for size in range(5000, 50001, 5000):
with open(f"random_array_{size}.txt", 'r') as f:
array = [int(line.strip()) for line in f]
runtime = measure_quick_sort_runtime(array)
random_runtimes.append(runtime)
sorted_runtimes = []
for size in range(5000, 50001, 5000):
with open(f"sorted_array_{size}.txt", 'r') as f:
array = [int(line.strip()) for line in f]
runtime = measure_quick_sort_runtime(array)
sorted_runtimes.append(runtime)
Department of Computer Engineering
plt.xlabel('Input Size')
plt.ylabel('Runtime (seconds)')
plt.title('Quick Sort Runtime Analysis')
plt.legend()
plt.show()
Output