USING RECURSION:
#include <stdio.h>
// Function to swap two elements
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Partition function
int partition(int arr[], 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;
}
// Recursive QuickSort
void quickSortRecursive(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSortRecursive(arr, low, pi - 1);
quickSortRecursive(arr, pi + 1, high);
}
}
// Print array
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main() {
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original Array:\n");
printArray(arr, n);
quickSortRecursive(arr, 0, n - 1);
printf("Sorted Array (Recursive QuickSort):\n");
printArray(arr, n);
return 0;
}
USING NO RECURSION:
#include <stdio.h>
// Function to swap two elements
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Partition function
int partition(int arr[], 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;
}
// Iterative QuickSort
void quickSortIterative(int arr[], int l, int h) {
int stack[h - l + 1];
int top = -1;
// Push initial values
stack[++top] = l;
stack[++top] = h;
while (top >= 0) {
h = stack[top--];
l = stack[top--];
int p = partition(arr, l, h);
// If left side exists, push to stack
if (p - 1 > l) {
stack[++top] = l;
stack[++top] = p - 1;
}
// If right side exists, push to stack
if (p + 1 < h) {
stack[++top] = p + 1;
stack[++top] = h;
}
}
}
// Print array
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main() {
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original Array:\n");
printArray(arr, n);
quickSortIterative(arr, 0, n - 1);
printf("Sorted Array (Non-Recursive QuickSort):\n");
printArray(arr, n);
return 0;
}