DAA Lab Program-2
DAA Lab Program-2
Write C/C++ programs to sort a given set of n integer elements using Quick Sort method
and compute its time Complexity. Run the program for varied values of n> 5000 and
record the time taken to sort. Plot a graph of the time taken versus non graph sheet. The
elements can be read from a file or can be generated using the random number generator.
Demonstrate using C/C++ how the divide-and-conquer method works along with its time
complexity analysis: worst case, average case and best case.
// Partition function
int partition(int arr[], int low, int high)
{
while (i < j) {
// QuickSort function
void quickSort(int arr[], int low, int high)
{
if (low < high) {
// driver code
int main()
{
int n, i;
clock_t start, end;
double time_taken;
int arr[n];
quickSort(arr, 0, n - 1);
return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
int n, i;
clock_t start, end;
double time_taken;
int arr[n];
quick_sort(arr, 0, n - 1);
return 0;
}
The above program generates an array of n random integers between 0 and 9999
using the rand() function from the stdlib.h library. It then sorts the array using the
quick_sort() function and records the time taken using the clock() function from
the time.h library.
The quick_sort() function implements the Quick Sort algorithm using the
partition() function to determine the pivot index. The function recursively sorts the
two partitions of the array on either side of the pivot index.
The time complexity of Quick Sort algorithm can be analyzed using three cases:
worst case, average case, and best case.
Worst Case: The worst case occurs when the partitioning process always picks the
greatest or smallest element as the pivot. In this case, the algorithm makes n - 1
comparisons at each level of recursion, resulting in a time complexity of O(n^2).
Average Case: The average case occurs when the pivot is chosen randomly and the
partition divides the array roughly into two equal parts. In this case, the time
complexity is O(n log n).
Best Case: The best case occurs when the partitioning process always picks the
median element as the pivot. In this case, the algorithm makes log n comparisons
at each level of recursion, resulting in a time complexity of