Untitled
unknown
plain_text
2 months ago
2.2 kB
9
Indexable
#include <stdio.h>
#include <time.h>
#define MAX 100
// Function to swap elements
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
// Partition function
int partition(int a[], int low, int high) {
int pivot = a[high]; // choose last element as pivot
int i = low - 1;
for (int j = low; j < high; j++) {
if (a[j] < pivot) {
i++;
swap(&a[i], &a[j]);
}
}
swap(&a[i + 1], &a[high]);
return i + 1;
}
// Quick Sort function
void quickSort(int a[], int low, int high) {
if (low < high) {
int pi = partition(a, low, high);
quickSort(a, low, pi - 1);
quickSort(a, pi + 1, high);
}
}
int main() {
int n, a[MAX];
clock_t start, end;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter elements:\n");
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
start = clock(); // start time
quickSort(a, 0, n - 1);
end = clock(); // end time
printf("Sorted array:\n");
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
double time_taken = (double)(end - start) / CLOCKS_PER_SEC;
printf("\nTime taken: %f seconds\n", time_taken);
return 0;
}
}
}
}
}
}
}
}Editor is loading...
Leave a Comment