Answers for "how to sort the elemets in c"

6

sorting program in c

#include<stdio.h>
int main(){
   /* Here i & j for loop counters, temp for swapping,
    * count for total number of elements, number[] to
    * store the input numbers in array. You can increase
    * or decrease the size of number array as per requirement
    */
   int i, j, count, temp, number[25];

   printf("How many numbers u are going to enter?: ");
   scanf("%d",&count);

   printf("Enter %d elements: ", count);
   // Loop to get the elements stored in array
   for(i=0;i<count;i++)
      scanf("%d",&number[i]);
 
   // Logic of selection sort algorithm
   for(i=0;i<count;i++){
      for(j=i+1;j<count;j++){
         if(number[i]>number[j]){
            temp=number[i];
            number[i]=number[j];
            number[j]=temp;
         }
      }
   }

   printf("Sorted elements: ");
   for(i=0;i<count;i++)
      printf(" %d",number[i]);

   return 0;
}
Posted by: Guest on October-08-2020
0

sorting in structure with c

#include <stdio.h>

struct student
{
    int rollno;
    char name[80];
    int marks;
};

void accept(struct student list[], int s);
void display(struct student list[], int s);
void bsortDesc(struct student list[], int s);

int main()
{
    struct student data[20];
    int n;

    printf("Number of records you want to enter? : ");
    scanf("%d", &n);

    accept(data, n);
    printf("nBefore sorting");
    display(data, n);
    bsortDesc(data, n);
    printf("nAfter sorting");
    display(data, n);

    return 0;
} 

void accept(struct student list[80], int s)
{
    int i;
    for (i = 0; i < s; i++)
    {
        printf("nnEnter data for Record #%d", i + 1);
        
        printf("nEnter rollno : ");
        scanf("%d", &list[i].rollno);

        printf("Enter name : ");
        gets(list[i].name);

        printf("Enter marks : ");
        scanf("%d", &list[i].marks);
    } 
}

void display(struct student list[80], int s)
{
    int i;
    
    printf("nnRollnotNametMarksn");
    for (i = 0; i < s; i++)
    {
        printf("%dt%st%dn", list[i].rollno, list[i].name, list[i].marks);
    } 
}

void bsortDesc(struct student list[80], int s)
{
    int i, j;
    struct student temp;
    
    for (i = 0; i < s - 1; i++)
    {
        for (j = 0; j < (s - 1-i); j++)
        {
            if (list[j].marks < list[j + 1].marks)
            {
                temp = list[j];
                list[j] = list[j + 1];
                list[j + 1] = temp;
            } 
        }
    }
}
Posted by: Guest on June-16-2021

Code answers related to "how to sort the elemets in c"

Browse Popular Code Answers by Language