You are on page 1of 4

Name: Parth Mehta

Roll No: 65
Branch: AIML
Experiment 1: Develop a code for Quick Sort
Aim: - To develop a code for Quick Sort
Theory: -
The quicksort algorithm sorts an unordered list based on the divide and conquer strategy. It
divides the unordered list into two sub-lists: low elements sub-list and high elements sub-list,
and then recursively sort these sub-lists.

Algorithm:
Let array[max] is integer array, low is string index of array, high is ending index of array
1. If(low<high)
2. i=low
3. j=high
4. while(i<j)
5. while((array[i]<=array[pivot])&&(i<high))
6. i++
7. while(array[j]>array[pivot])
8. j - -
9. if(i<j)
10. temp=array[i]
11. array[i]=array[j]
12. array[j]=temp
13. temp=array[pivot]
14. array[pivot]=array[j]
15. array[j]=temp
16. quick(array,low,j-1)
17. quick(array,j+1,high)

Time Analysis of Quick Sort


In general time taken by Quick Sort is written as:
T(n) = T(k) + T(n-k-1) + Ө(n)
Worst Case:
In quick sort, worst case occurs when the pivot element is either greatest or smallest
element. Suppose, if the pivot element is always the last element of the array, the worst
case would occur when the given array is sorted already in ascending or descending order.
The worst-case time complexity of quicksort is O(n2).

Best Case:
In Quicksort, the best-case occurs when the pivot element is the middle element or near to
the middle element. The best-case time complexity of quicksort is O(n*logn).
Name: Parth Mehta
Roll No: 65
Branch: AIML
Average Case:
It occurs when the array elements are in jumbled order that is not properly ascending and not
properly descending. The average case time complexity of quicksort is O(n*logn).

Implementation: -
Program Code:
#include <stdio.h>
void quicksort (int [], int, int);
void main()
{
int list[50];
int size, i;
printf("Enter the number of elements: ");
scanf("%d", &size);
printf("Enter the elements to be sorted:\n");
for (i = 0; i < size; i++)
{
scanf("%d", &list[i]);
}
quicksort(list, 0, size - 1);
printf("After applying quick sort\n");
for (i = 0; i < size; i++)
{
printf("%d ", list[i]);
}
printf("\n");
}
void quicksort(int list[], int low, int high)
{
int pivot, i, j, temp;
if (low < high)
Name: Parth Mehta
Roll No: 65
Branch: AIML
{
pivot = low;
i = low;
j = high;
while (i < j)
{
while (list[i] <= list[pivot] && i <= high)
{
i++;
}
while (list[j] > list[pivot] && j >= low)
{
j--;
}
if (i < j)
{
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
temp = list[j];
list[j] = list[pivot];
list[pivot] = temp;
quicksort(list, low, j - 1);
quicksort(list, j + 1, high);
}
}
Name: Parth Mehta
Roll No: 65
Branch: AIML
Output:

Conclusion: -
Thus, we learnt how to calculate Time Complexity for Quick Sort Algorithm and implement
it using C Programming Language.

Course Outcomes: -
1. Analyse the complexities of various problems in different domains.
Learning Outcomes: -
1. To learn how to develop code for sorting algorithm and analyse time
complexity.

You might also like