Skip to content

Instantly share code, notes, and snippets.

@sortira
Created November 20, 2025 05:13
Show Gist options
  • Select an option

  • Save sortira/28965352c8be694df92435e63074198a to your computer and use it in GitHub Desktop.

Select an option

Save sortira/28965352c8be694df92435e63074198a to your computer and use it in GitHub Desktop.
quicksort.c
#include<stdlib.h>
#include<stdio.h>
#include<time.h>
int partition(int* a, int p, int r) {
int x = a[p];
int i = p;
for(int j = p + 1; j < r; j++) {
if(a[j] <= x) {
i++;
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
int temp = a[i];
a[i] = a[p];
a[p] = temp;
return i;
}
void quick_sort(int* a, int p, int r) {
if(p < r) {
int q = partition(a, p, r);
quick_sort(a, p, q - 1);
quick_sort(a, q + 1, r);
}
}
int main() {
char filename[1000];
printf("Enter file name:\n");
scanf("%s", filename);
FILE* file = fopen(filename, "rw");
int length;
fscanf(file, " %d", &length);\
printf("Length of array %d\n", length);
int* array1 = (int*) malloc(sizeof(int) * (length));
for(int i = 0; i < length; i++) {
fscanf(file, " %d", &array1[i]);
}
clock_t start_time, end_time;
double quicksort_time_taken_ms;
printf("Quick Sort Trial:\n");
start_time = clock();
quick_sort(array1, 0, length);
end_time = clock();
quicksort_time_taken_ms = ((double)(end_time - start_time)) / CLOCKS_PER_SEC * 1000.0;
printf("Time Taken for Quick Sort: %f milliseconds.\n", quicksort_time_taken_ms);
printf("\n");
// printf("Results of Quick Sort:\n");
// for(int i = 0; i < length; i++) {
// printf("%d ", array1[i]);
// }
// printf("\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment