Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #include<math.h>
- void RunSort(void);
- void InsertionSort(void);
- void SelectionSort(void);
- void BubbleSort(void);
- void genNumtoFile(void);
- void savetofile(void);
- int totalNum = 5, values[100];
- int main(){
- genNumtoFile();
- RunSort();
- savetofile();
- }
- void RunSort(){
- int choice;
- time_t start, end;
- start = time(NULL);
- while (1){
- printf("\n\nIn which method you want to sort?\n\n");
- printf(" 1> Insertion Sort\n");
- printf(" 2> Selection Sort\n");
- printf(" 3> Bubble Sort\n");
- printf(" 4> Save\n");
- printf(" 5> To terminate!\n");
- scanf("%d", &choice);
- end = time(NULL);
- double timePassed = difftime(end, start);
- switch (choice){
- case 1:
- InsertionSort();
- printf("Time taken: %.2f seconds\n", timePassed);
- break;
- case 2:
- SelectionSort();
- printf("Time taken: %.2f seconds\n", timePassed);
- break;
- case 3:
- BubbleSort();
- printf("Time taken: %.2f seconds\n", timePassed);
- break;
- case 5:
- exit(0);
- case 4:
- savetofile();
- printf("\nData is saved successfully\n");
- break;
- }
- }
- }
- void genNumtoFile(){
- int i;
- FILE *fp;
- errno_t err = fopen_s(&fp, "valuesGenerated.txt", "w");
- for (i = 0; i<totalNum; i++){
- values[i] = rand() % 1000;
- fprintf_s(fp, "%d\n", values[i]);
- }
- fclose(fp);
- printf("Randomly generated values are:\n \n");
- for (i = 0; i < totalNum; i++){
- printf("\t%d", values[i]);
- }
- }
- void InsertionSort(){
- int i, t, j;
- for (j = 1; j< totalNum; j++) {
- t = values[j];
- i = j - 1;
- while (i >= 0 && values[i] > t) {
- values[i + 1] = values[i];
- i = i - 1;
- }
- values[i + 1] = t;
- }
- printf("\nInsertion SORT : ");
- for (i = 0; i< totalNum; i++) {
- printf(" %d ", values[i]);
- }
- printf("\n");
- }
- void SelectionSort(){
- int i, j, t, k, tmp;
- for (j = totalNum - 1; j >= 2; j--){
- t = 1;
- for (k = 2; k <= j; k++){
- if (values[k] > values[t]){
- t = k;
- }
- }
- tmp = values[t];
- values[t] = values[j];
- values[j] = tmp;
- }
- printf("\nSelection Sort : ");
- for (i = 0; i< totalNum; i++) {
- printf(" %d ", values[i]);
- }
- printf("\n");
- }
- void BubbleSort(){
- int i, j, temp;
- for (i = 0; i < totalNum - 1; i++){
- for (j = 0; j < totalNum - 1; j++){
- if (values[j] > values[j + 1]) {
- temp = values[j];
- values[j] = values[j + 1];
- values[j + 1] = temp;
- }
- }
- }
- printf("\n\n Bubble sort : ");
- for (i = 0; i < totalNum; i++){
- printf("%d ", values[i]);
- }
- printf("\n");
- }
- void savetofile(){
- int i;
- FILE *fp;
- errno_t err = fopen_s(&fp, "Sortedvalues.txt", "w");
- for (i = 0; i<totalNum; i++){
- fprintf_s(fp, "%d\n", values[i]);
- }
- fclose(fp);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement