Sort data using Selection Sort - C Program

Write a C program to create a file named as “products.txt”. Store names of some products. Then read those names from the same file and sort them in ascending order using selection sort. Finally print them.

Solution:

Selection Sort:
In this sorting algorithm the list is divided into two parts. The left part is sorted and right part of the list is unsorted. The smallest element compared to all remaining elements and swapped with that element.

In this sorting technique, the first element compared to all the element and finding the minimum element and replace it to left side of array.

Program

#include <stdio.h>
#include <string.h>
#define max 100
struct nick
{
char a[20];
};
                                                 //function for selection sort
void selection(struct nick items[], int);

int main()
{
    FILE *fp;                                    //file pointer
    int i=0,k=0,n;
    char fname[20],str[20],c;
    struct nick name[max];
    printf("Enter the filename : ");
    scanf("%s",fname);
    printf("\nEnter the number of products: ");
    scanf("%d",&n);
    printf("Enter %d product name : \n",n);
    fp=fopen(fname,"w");                          //opening file in write mode
    for(i=0;i<n;i++)
    {
        scanf("%s",name);
        fprintf(fp,"%s ",name);                   //writing it on file
    }
    fclose(fp);
    i=0;

    fp=fopen(fname,"r");                           //opening file in read mode
    while((c=getc(fp))!=EOF)
    {
        if(c==' ')
            {
                str[i]='\0';
                strcpy(name[k].a,str);
                i=0;
                k++;
            }
        else
        {
            str[i]=c;
            i++;
        }
    }
    fclose(fp);                                      //close file pointer
    printf("\nInitial contents of file: \n");
    for(i=0; i<k; i++)
        printf("%s,", name[i].a);                     //printing initial contents

    selection(name,k);                               //calling selection sort

    printf("\n\nAfter applying selection sort: \n");
    for(i=0; i<k; i++)
    {
         printf("%s,", name[i].a);                    //result after swapping
    }
    return 0;
}

void selection(struct nick items[], int n)
{
    int i=0,j=0,pos=0;
    char min[20];
    char temp[10];
    for(i=0;i<n-1;i++)
    {
         strcpy(min,items[i].a);                      //copy the items at i'th index in min
         pos=i;
         for(j=i+1;j<n;j++)
         {
              if(strcmp(min,items[j].a)>0)
              {
                   strcpy(min,items[j].a);
                   pos=j;
              }
         }
         if(pos!=i)
         {
              strcpy(temp,items[i].a);        //swap item[pos] and item[i]
              strcpy(items[i].a,min);
              strcpy(items[pos].a,temp);
         }    
     }
}


Output:

selection sort