5.
Write a program to sort an array of integers implementing Quick sort using Divide
and Conquer strategy.
#include <iostream>
using namespace std;
class QuickSort {
private:
int arr[100], n;
// Partition function
int partition(int low, int 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;
}
public:
void input() {
cout << "Enter number of elements: ";
cin >> n;
cout << "Enter elements:\n";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
}
// Quick Sort function (Divide and Conquer)
void quickSort(int low, int high) {
if (low < high) {
int pi = partition(low, high);
quickSort(low, pi - 1); // Left subarray
quickSort(pi + 1, high); // Right subarray
}
}
void display() {
cout << "Sorted array:\n";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int getSize() {
return n;
}
};
int main() {
QuickSort qs;
[Link]();
[Link](0, [Link]() - 1);
[Link]();
return 0;
}
Input:
Enter number of elements: 5
Enter elements:
10 7 8 9 1
Output:
Sorted array:
1 7 8 9 10