Files
sibsutis/1Y-2H/dsa/lab2/code/main.c
T
2026-03-06 12:33:18 +07:00

142 lines
4.0 KiB
C

#include "head.h"
#include <time.h>
double get_time();
void fill_rand(uint32_t *arr, int n);
int main(int argc,char **argv) {
srand(get_time());
if(argc>1){
switch(argv[1][0]){
case '1': // Exp what sort is faster
run_exp();
break;
case '2': // Test Sorts
{
int n;
if(!(argv[1][1]>='a'&&argv[1][1]<='z')){
printf("\nPrint 2(r/h/b/m) to sort or 3 to see var");
printf("\n2r - radix\n2h - heap\n2b - bubble\n2m - merge\n");
return 0;}
printf("Write n:");
scanf("%d",&n);
while(getchar()>'\n');
uint32_t *arr = (uint32_t*)malloc(sizeof(uint32_t) * n);
printf("Write n nums:");
for (int i = 0;i<n;i++){
scanf("%d",&arr[i]);
}
for(int i = 0; i<n;i++)printf("%d ",arr[i]);
putchar('\n');
switch(argv[1][1]){
case 'r': // Radix
sort_radix(arr,n);
for(int i = 0; i<n;i++)printf("%d ",arr[i]);
break;
case 'h': // Heap
sort_heap(arr,n);
for(int i = 0; i<n;i++)printf("%d ",arr[i]);
break;
case 'b': //Bubble
sort_bubble(arr,n);
for(int i = 0; i<n;i++)printf("%d ",arr[i]);
break;
case 'm': //Merge
sort_merge(arr,0,n-1);
for(int i = 0; i<n;i++)printf("%d ",arr[i]);
break;
default:
printf("\nPrint 2(r/h/b/m) to sort or 3 to see var");
printf("\n2r - radix\n2h - heap\n2b - bubble\n2m - merge\n");
return 0;
}
free(arr);
break;
}
case '3':
{
printf("\n N - %d",(18-1)%24+1);
break;
}
default:
{
printf("\nPrint 2(r/h/b/m) to sort or 3 to see var");
printf("\n2r - radix\n2h - heap\n2b - bubble\n2m - merge\n");
return 0;
}
}
}
else{
run_exp();
}
return 0;
}
void run_exp(void) {
FILE *f = fopen("table.dat", "w");
if (!f) return;
fprintf(f, "# N Radix Heap Bubble \n");
int n = MILLION,end=MILLION,step = 50000;
for (;n<=end;n+=step){
uint32_t *arrA = (uint32_t*)malloc(sizeof(uint32_t) * n);
uint32_t *arrB = (uint32_t*)malloc(sizeof(uint32_t) * n);
uint32_t *arrC = (uint32_t*)malloc(sizeof(uint32_t) * n);
double tRadTotal = 0;
double tHeapTotal = 0;
double tBubblTotal = 0;
for (int i = 0; i < AVG_TIME_LOOPS; i++) {
fill_rand(arrA, n);
arrC = arrB = arrA;
double ta = get_time();
sort_radix(arrA,n);
tRadTotal += (get_time() - ta);
double tb = get_time();
sort_heap(arrB, n);
tHeapTotal += (get_time() - tb);
double tc = get_time();
sort_bubble(arrC,n);
tBubblTotal += (get_time() - tc);
}
double tRadRes = tRadTotal / AVG_TIME_LOOPS;
double tHeapRes = tHeapTotal / AVG_TIME_LOOPS;
double tBubblRes = tBubblTotal / AVG_TIME_LOOPS;
free(arrA);
free(arrB);
free(arrC);
fprintf(f, "%d %f %f %f\n", n, tRadRes, tHeapRes, tBubblRes);
printf("Sort: %d/%d \r", n, end);
fflush(stdout);
}
fclose(f);
printf("\nTable 1 done.\n");
return;
}
int get_rand(int min, int max) {
return (double)rand() / (RAND_MAX + 1.0) * (max - min) + min;
}
void fill_rand(uint32_t *arr, int n) {
for (int i = 0; i < n; i++) arr[i] = get_rand(0, AVG_RAND_MAX);
}
double get_time() {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec + ts.tv_nsec * 1e-9;
}