Program-02
Program-02
Subject Code:21CS42
Program-02
2. 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 n. The
elements can be read from a file or can be generated using the random
number generator. Demonstrate using C++/Java how the divide-and-conquer
method works along with its time complexity analysis: worst case, average
case and best case.
Divide: Rearrange the elements and split arrays into two sub-arrays and an element
in between search that each element in left sub array is less than or equal to the
average element and each element in the right sub- array is larger than the middle
element.
ALGORITHM
1. Find a “pivot” item in the array. This item is the basis for
comparison for a single round.
2. Start a pointer (the left pointer) at the first item in the array.
3. Start a pointer (the right pointer) at the last item in the array.
4. While the value at the left pointer in the array is less than the
pivot value, move the left pointer to the right (add 1). Continue
until the value at the left pointer is greater than or equal to the
pivot value.
5. While the value at the right pointer in the array is greater than
the pivot value, move the right pointer to the left (subtract 1).
Continue until the value at the right pointer is less than or equal
to the pivot value.
6. If the left pointer is less than or equal to the right pointer, then
swap the values at these locations in the array.
7. Move the left pointer to the right by one and the right pointer to
the left by one.
Example:
Time Complexities:
Worst Case Analysis: It is the case when items are already in sorted form and we try to sort
them again. This will takes lots of time and space.
Average Case: Generally, we assume the first element of the list as the pivot element.
In an average Case, the number of chances to get a pivot element is equal to the number
of items
Best Case: In any sorting, best case is the only case in which we don't make any comparison
between elements that is only done when we have only one element to sort.
PROGRAM
import java.util.Random;
import java.util.Scanner;
}
static void Quick(int a[],int low,int high) {
int m,i;
if(low<high) {
m = Partition(a, low, high);
Quick(a, low, m-1);
Quick(a,m+1,high);
}
}
Search Creators… Page 6
21CS42 | DESIGN & ANALYSIS OF ALGORITHM | SEARCH CREATORS
}
static void swap(int a[], int i, int j) {
int temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
OUTPUT