-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquickSort-C
More file actions
111 lines (87 loc) · 2.11 KB
/
quickSort-C
File metadata and controls
111 lines (87 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#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 a[], int low, int high)
{
int pivot = a[low];
int i = low + 1;
int j = high;
while(1)
{
while(i <= high && a[i] <= pivot)
i++;
while(a[j] > pivot)
j--;
if(i < j)
swap(&a[i], &a[j]);
else
break;
}
swap(&a[low], &a[j]);
return j;
}
void quickSort(int a[], int low, int high)
{
if(low < high)
{
int p = partition(a, low, high);
quickSort(a, low, p - 1);
quickSort(a, p + 1, high);
}
}
// generate random numbers
void generateRandomNumbers(int a[], int n)
{
for(int i = 0; i < n; i++)
a[i] = rand() % 10000;
}
int main()
{
int a[10000];
clock_t start, end;
double time_taken;
double theoretical_time;
FILE *fp;
srand((unsigned)time(NULL));
fp = fopen("q_time.txt", "w");
if(fp == NULL)
{
printf("File cannot be opened\n");
return 1;
}
for(int n = 100; n < 10000; n += 100)
{
generateRandomNumbers(a, n);
start = clock();
quickSort(a, 0, n - 1);
end = clock();
time_taken = (double)(end - start) / CLOCKS_PER_SEC;
// theoretical n log n
theoretical_time = (double)(n * log(n)) * 1e-7;
fprintf(fp, "%d %lf %lf\n", n, time_taken, theoretical_time);
}
fclose(fp);
FILE *gP = popen("gnuplot -persistent", "w");
if(gP == NULL)
{
printf("Gnuplot not found\n");
return 1;
}
fprintf(gP, "set title 'Quick Sort Time Efficiency'\n");
fprintf(gP, "set xlabel 'Input Size'\n");
fprintf(gP, "set ylabel 'Time (seconds)'\n");
fprintf(gP, "set grid\n");
fprintf(gP, "set term png\n");
fprintf(gP, "set output 'Q_sort_efficiency_c.png'\n");
fprintf(gP, "plot 'q_time.txt' using 1:2 with linespoints title 'Actual Time',");
fprintf(gP, "'q_time.txt' using 1:3 with lines lw 2 title 'Theoretical Time'\n");
fflush(gP);
pclose(gP);
return 0;
}