0% found this document useful (0 votes)
13 views

Quick Sort

Uploaded by

Ms Anushree G
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Quick Sort

Uploaded by

Ms Anushree G
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

#include <stdio.

h>

#include <stdlib.h>

#include <time.h>

void swap(int* a, int* b) {

int t = *a;

*a = *b;

*b = t;

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 printArray(int arr[], int size) {

for (int i = 0; i < size; i++) {

printf("%d ", arr[i]);

printf("\n");

int main() {

srand(time(0));

int n;

printf("Enter the number of elements: ");

scanf("%d", &n);

int *arr = (int *)malloc(n * sizeof(int));

if (arr == NULL) {

printf("Memory not allocated.\n");

exit(0);

for (int i = 0; i < n; i++) {

scanf("%d",&arr[i]);

// arr[i] = rand();

printf("Generated array: \n");

printArray(arr, n);

quickSort(arr, 0, n - 1);
printf("Sorted array: \n");

printArray(arr, n);

free(arr);

return 0;

PART2

int main() {

FILE *fptr;

fptr = fopen("results.csv", "w");

if (fptr == NULL) {
printf("Error opening file!\n");

return 1;

srand(time(0));

fprintf(fptr, "Number of Elements,Time Taken (seconds)\n");

for (int n = 5000; n <= 50000; n += 5000) {

int *arr = (int *)malloc(n * sizeof(int));

if (arr == NULL) {

printf("Memory not allocated.\n");

exit(0);

for (int i = 0; i < n; i++) {

arr[i] = rand();

clock_t start, end;

double cpu_time_used;

start = clock();

quickSort(arr, 0, n - 1);

end = clock();

cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;

printf("Time taken to sort %d elements: %f seconds\n", n, cpu_time_used);

fprintf(fptr, "%d,%f\n", n, cpu_time_used);


free(arr);

fclose(fptr);

return 0;

You might also like