https://www.geeksforgeeks.org/sorting-integer-data-from-file-and-calculate-execution-time/
Sorting integer data from file and calculate execution time
Prerequisite: Selection Sort
In this article, we are going to apply selection sort algorithm, in which the source of input is A FILE CONTAINING 10000 INTEGERS and output will be the total time taken to sort.
Important functions to be used:
- rand(): Used to generate random numbers.
- fopen(): Used to open file .
- fscanf(): Used to scan data from file .
- clock(): Return the number of clock cycle
Program to generate random number in a file “random.txt”
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
FILE * fptr;
fptr = fopen ( "random.txt" , "w" );
int i;
if (fptr == NULL) {
printf ( "ERROR" );
exit (1);
}
for (i = 0; i < 10000; i++) {
int val = rand () % 100000;
fprintf (fptr, "%d " , val);
}
fclose (fptr);
printf ( "numbers generated successfully !! " );
return 0;
}
|
- clock_t or Clock ticks are units of time of a constant but system-specific length, as those returned by function clock.
Algorithm for this program:
- Open the file using fopen().
- Scan the file and copy it to the array using fscanf().
- Apply any sorting algorithm that you want.
- Print to console.
Below are the implementation of above algorithm.
#include <stdio.h>
#include <time.h>
int main()
{
clock_t starttime, endtime;
double totaltime;
int i = 0, j, n = 0, min, index;
int arr[100000];
FILE * fptr;
fptr = fopen ( "random.txt" , "r" );
while ( fscanf (fptr, "%d" , &arr[i]) == 1)
{
n++;
i++;
}
starttime = clock ();
printf ( "start time : %f\n" , ( float )starttime);
for (i = 0; i < n - 1; i++) {
min = arr[i];
for (j = i + 1; j < n; j++) {
if (arr[j] < min) {
min = arr[j];
index = j;
}
}
int temp = arr[i];
arr[i] = min;
arr[index] = temp;
}
endtime = clock ();
printf ( "%f\n" , ( float )endtime);
totaltime = (( double )(endtime - starttime)) / CLOCKS_PER_SEC;
for (i = 0; i < n; i++)
printf ( "%d " , arr[i]);
printf ( "\n\nendtime : %f\n" , ( float )endtime);
printf ( "\n\ntotal time of execution = %f" , totaltime);
return 0;
}
|
No hay comentarios:
Publicar un comentario