Explain the concept of Sorting in C language


Problem

Why sorting makes searching easier in C language? How can you judge the sorting efficiency in C?

Solution

Sorting is the process of arranging elements either in ascending (or) descending order.

  • The term sorting came into existence when humans realized the importance of searching quickly.

  • There are different things in life that we need to search for, particular record in database, roll numbers in a list, a number in a telephone directory, a specific page in a book etc.

  • If the data was kept in an unordered and unsorted form, it becomes difficult to search a particular thing. But fortunately, the concept of sorting came into existence, making it easier for everyone to arrange data in an order.

  • Sorting arranges data in a sequence which makes searching easier.

Sorting Efficiency

  • If we want to arrange a deck of cards in order, we will start by checking every card, and accordingly, make the deck as we move on.

  • It takes so much of time to arrange the deck in order, yet we do it in the same manner. But, computers don't work like this.

  • From the beginning of the programming age, scientists have been working on solving the problem of sorting by different algorithms to sort the data.

The criteria to judge which algorithm is better than the other is as follows −

  • Time taken to sort the given data.
  • Memory Space required to do so.

Example

Following is the C program for sorting the data −

#include<stdio.h>
int main(){
   int a[50], i,j,n,t,sm;
   printf("enter the No: of elements in the list:
");    scanf("%d", &n);    printf("enter the elements:
");    for(i=0; i<n; i++){       scanf ("%d", &a[i]);    }    for (i=0; i<n-1; i++){       sm=i;       for (j=i+1; j<n; j++){          if (a[j] < a[sm]){             sm=j;          }       }       t=a[i];       a[i]=a[sm];       a[sm]=t;    }    printf ("after selection sorting the elements are:
");    for (i=0; i<n; i++)       printf("%d\t", a[i]);    return 0; }

Output

When the above program is executed, it produces the following result −

Output

enter the No: of elements in the list:
4
enter the elements:
34
12
56
7
after selection sorting the elements are:
7 12 34 56

Updated on: 11-Mar-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements