-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertionSort-c
More file actions
88 lines (69 loc) · 1.77 KB
/
insertionSort-c
File metadata and controls
88 lines (69 loc) · 1.77 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
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void insertionSort(int a[], int n)
{
int key, j;
for(int i = 1; i < n; i++)
{
key = a[i];
j = i - 1;
while(j >= 0 && a[j] > key)
{
a[j + 1] = a[j];
j = j - 1;
}
a[j + 1] = key;
}
}
// function to generate random numbers between 0 - 9999
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("i_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();
insertionSort(a, n);
end = clock();
time_taken = (double)(end - start) / CLOCKS_PER_SEC;
theoretical_time = (double)(n * n) * 1e-8;
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 'Insertion 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 'I_sort_efficiency_c.png'\n");
fprintf(gP, "plot 'i_time.txt' using 1:2 with linespoints title 'Actual Time',");
fprintf(gP, "'i_time.txt' using 1:3 with lines lw 2 title 'Theoretical Time'\n");
fflush(gP);
pclose(gP);
return 0;
}