Question 1:
Write an algorithm that choose first element as pivot using quick sort.
partition(int arr[], int low, int high)
int pivot = arr[low],st = low,end = high,k = high
for (int i = high; i > low; i--) {
if (arr[i] > pivot)
swap(arr[i], arr[k--])
swap(arr[low], arr[k])
return k;
void quickSort(int arr[];
int low, int high)
if (low < high)
int idx = partition(arr, low, high)
quickSort(arr, low, idx - 1)
quickSort(arr, idx + 1, high)
Program
#include <iostream>
using namespace std;
int partition(int arr[], int low, int high) {
int pivot = arr[low];
int i = low + 1;
for (int j = low + 1; j <= high; j++) {
if (arr[j] < pivot) {
// Swap arr[i] and arr[j]
swap(arr[i], arr[j]);
i++;
swap(arr[low], arr[i - 1]);
return i - 1;
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pivotIndex = partition(arr, low, high);
quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
cout <<endl;
int main() {
int arr[] = {
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Original array is: ";
printArray(arr, n);
quickSort(arr, 0, n - 1);
cout << "Sorted array is : ";
printArray(arr, n);
return 0;
Output
Question 2
Write an algorithm that choose random element as pivot using quick sort.
procedure partition (arr[], start, end)
pickRandom (arr, start, end)
pivot = arr[end]
i = start
for k = start to end – 1
if arr[k] <= pivot
swap arr[k] and arr[i]
i=i+1
end if
end for
swap arr[i] and arr[end]
return i
end procedure
procedure quickSort (arr[], start, end)
if start < end
p = pickRandom (arr[], start, end)
quickSort (arr[], start, p-1)
quickSort (arr[], p+1, end)
end if
end procedure
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
// Function to partition the array and return the pivot index
int partition(int arr[], int low, int high) {
// Generate a random index between low and high
int randomIndex = low + rand() % (high - low + 1);
// Swap the randomly chosen element with the last element
swap(arr[randomIndex], arr[high]);
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i + 1], arr[high]);
return i + 1;
}
// Function to perform quicksort
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pivotIndex = partition(arr, low, high);
// Recursively sort the subarrays
quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
int main() {
srand(time(0)); // Seed for random number generation
int arr[] =
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Original array: ";
printArray(arr, n);
quickSort(arr, 0, n - 1);
cout << "Sorted array: ";
printArray(arr, n);
return 0;
}
output