Make any program regarding data input, save data, read data, search data and sort data (file, sorting and searchin
Write in C Language.
Make any program regarding data input, save data, read data, search data and sort data (file, sorting and searching)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
// write data input numbers to file
FILE* wfptr;
wfptr = fopen("file.txt", "w");
if (wfptr == NULL) {
printf("ERROR");
exit(1);
}
for (int i = 0; i < 5; i++) {
int val;
scanf("%d", &val);
// storing data to file
fprintf(wfptr, "%d ", val);
}
// closing the file
fclose(wfptr);
// data type for calculating time
clock_t starttime, endtime;
// variable for calculating total time of execution
double totaltime;
int i = 0, j, n = 0, min, index;
// declaring array
int arr[5];
// declaring file pointer
FILE* fptr;
// opening the integer file.
fptr = fopen("file.txt", "r");
// scanning integer from file to array
while (fscanf(fptr, "%d", &arr[i]) == 1)
{
// count elements from file //
n++;
i++;
}
starttime = clock();
printf("start time to sort : %f\n", (float)starttime);
// sort data
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;
}
// selection sort logic ends here
// calculating clock when sorting ends
endtime = clock();
printf("%f\n", (float)endtime);
totaltime = ((double)(endtime - starttime)) / CLOCKS_PER_SEC;
// printing the sorted array...
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n\nendtime after sort: %f\n", (float)endtime);
printf("\n\ntotal time of execution = %f", totaltime);
return 0;
}
Step by step
Solved in 2 steps with 1 images