Untitled
unknown
plain_text
2 years ago
2.3 kB
6
Indexable
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
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 quick_sort_recursive(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quick_sort_recursive(arr, low, pi - 1);
quick_sort_recursive(arr, pi + 1, high);
}
}
void quick_sort_iterative(int arr[], int low, int high) {
int stack[high - low + 1];
int top = -1;
stack[++top] = low;
stack[++top] = high;
while (top >= 0) {
high = stack[top--];
low = stack[top--];
int pi = partition(arr, low, high);
if (pi - 1 > low) {
stack[++top] = low;
stack[++top] = pi - 1;
}
if (pi + 1 < high) {
stack[++top] = pi + 1;
stack[++top] = high;
}
}
}
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n], arr_iter[n];
srand(time(NULL));
for (int i = 0; i < n; i++) {
arr[i] = rand() % 1000; // Random integers between 0 and 999
arr_iter[i] = arr[i]; // Copying for iterative quick sort
}
clock_t start, end;
double cpu_time_used;
// Recursive Quick Sort
start = clock();
quick_sort_recursive(arr, 0, n - 1);
end = clock();
cpu_time_used = ((double)(end - start)) / CLOCKS_PER_SEC;
printf("Sorted array using recursive quick sort: ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\nTime taken by recursive quick sort: %f seconds\n", cpu_time_used);
// Iterative Quick Sort
start = clock();
quick_sort_iterative(arr_iter, 0, n - 1);
end = clock();
cpu_time_used = ((double)(end - start)) / CLOCKS_PER_SEC;
printf("\nSorted array using iterative quick sort: ");
for (int i = 0; i < n; i++)
printf("%d ", arr_iter[i]);
printf("\nTime taken by iterative quick sort: %f seconds\n", cpu_time_used);
return 0;
}
Editor is loading...
Leave a Comment