Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

DAA PRACTICAL-3

NIRAJ GAJERA – 23MCA016

Write program to implement Quick Sort algorithm by randomly


selecting any element of an array as the pivot element. Display the
output after each call to the "PARTITION" function finishes.

#include <iostream>
#include <cstdlib>
#include<time.h>
using namespace std;
int partition(int *a, int s, int e)
{ int pivot = a[s]; int i = s
+ 1; for (int j = s + 1; j <= e;
j++) { if (a[j] < pivot) {
swap(a[i], a[j]); i++;
} }
swap(a[s], a[i - 1]);
return i - 1;
}
int pick_random(int *a, int s, int e)
{ srand(time(0)); int r = s + rand() % (e - s);
cout << "Randomly selected pivot index: " << r << endl;
swap(a[r], a[s]);
return partition(a, s, e);
}
void quick_sort(int *a, int s, int e)
{ if (s >= e) return;
int p = pick_random(a, s,
e);
cout << "Array after
partition: ";

for (int i = 0; i <= 10; i++) {


cout << a[i] << " ";
} cout
<< endl;
quick_sort(a, s, p -
1); quick_sort(a, p +
1, e);
} int main() { int a[] = {34, 23, 2, 1, 23, 34,
DAA PRACTICAL-3
NIRAJ GAJERA – 23MCA016

12, 21, 32, 12};


int n = sizeof(a) / sizeof(a[0]);
cout << "Size of array: " << n << endl;
quick_sort(a, 0, n
- 1);
cout << "Array after sorting:
"; for (int i = 0; i < n; i++)
{ cout << a[i] << " ";
}
return 0;
}

OUTPUT :

You might also like