2CSBS4102-Design And Analysis Of Algorithm
Practical – 6
Q : 6 Write user defined functions for Randomized Quick sort and compare its performance with
normal version of quick sort using steps count on various number of inputs.
Code: #include <stdio.h>
#include <stdlib.h>
#include <time.h>
int steps_normal = 0, steps_random = 0;
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
steps_normal++;
if (arr[j] <= pivot) {
23012571013 U.V Patel College of Engineering Gayatri Solanki
2CSBS4102-Design And Analysis Of Algorithm
i++;
swap(&arr[i], &arr[j]);
swap(&arr[i + 1], &arr[high]);
return i + 1;
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
int randomizedPartition(int arr[], int low, int high) {
int random = low + rand() % (high - low + 1);
swap(&arr[random], &arr[high]);
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
23012571013 U.V Patel College of Engineering Gayatri Solanki
2CSBS4102-Design And Analysis Of Algorithm
steps_random++;
if (arr[j] <= pivot) {
i++;
swap(&arr[i], &arr[j]);
swap(&arr[i + 1], &arr[high]);
return i + 1;
void randomizedQuickSort(int arr[], int low, int high) {
if (low < high) {
int pi = randomizedPartition(arr, low, high);
randomizedQuickSort(arr, low, pi - 1);
randomizedQuickSort(arr, pi + 1, high);
void testSorting(int size) {
int *arr1 = (int *)malloc(size * sizeof(int));
int *arr2 = (int *)malloc(size * sizeof(int));
23012571013 U.V Patel College of Engineering Gayatri Solanki
2CSBS4102-Design And Analysis Of Algorithm
for (int i = 0; i < size; i++) {
int val = rand() % 1000;
arr1[i] = val;
arr2[i] = val;
steps_normal = steps_random = 0;
quickSort(arr1, 0, size - 1);
randomizedQuickSort(arr2, 0, size - 1);
printf("Input size: %d\n", size);
printf("Normal QuickSort steps: %d\n", steps_normal);
printf("Randomized QuickSort steps: %d\n\n", steps_random);
free(arr1);
free(arr2);
int main() {
srand(time(NULL));
int sizes[] = {10, 100, 500, 1000, 5000};
int num_sizes = sizeof(sizes) / sizeof(sizes[0]);
23012571013 U.V Patel College of Engineering Gayatri Solanki
2CSBS4102-Design And Analysis Of Algorithm
for (int i = 0; i < num_sizes; i++) {
testSorting(sizes[i]);
return 0;
Output:
23012571013 U.V Patel College of Engineering Gayatri Solanki