PROGRAM-4
AIM : Write a program for quick sort.
TOOLS USED : Visual Studio Code Editor
SOURCE CODE:
#include <iostream>
using namespace std;
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 - 1; j++) {
if (arr[j] < pivot) {
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);
}
}
void display(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];
cout << "Enter the elements: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
cout << "Array before sorting: ";
display(arr, n);
quickSort(arr, 0, n - 1);
cout << "Array after sorting: ";
display(arr, n);
return 0;
}
OUTPUT:
LEARNING OUTCOMES:
1.Understanding of Quick Sort Algorithm: Gained an understanding of the divide-and-
conquer approach used in Quick Sort, which involves partitioning an array and recursively
sorting the subarrays.
2. Recursive Problem Solving: Developed the ability to apply recursion in sorting algorithms,
breaking down a problem into smaller, manageable subproblems.
3. Time Complexity: Quick Sort is known for its average O(n log n) time complexity,
although in the worst case (e.g., when the array is already sorted), it can degrade to O(n²).