C Program to sort elements in an array


Generally for sorting elements in an array one use bubble sort method . In this bubble sorting method by the end of one inner for loop the largest element among all the numbers will be moved to top of the array i.e., it bubbles up. This is done by comparing the adjacent two numbers and swapping them so that those two will be in increasing order and finally the largest number is moved to the top of array. This process is continued by discarding the top element of the array and then bubble sort method is applied on the remaining elements. That is why inner for loop iterates only ‘(n-i) -1 ‘ times while outer for loop iterates (n-1) number of times to sort all given numbers in an array.

 C program to sort array elements


Source code:

#include<stdio.h>
#include<stdlib.h>

int main()
{
   int a[30],n,i,j,temp, sorted=0;
   printf("\n How many numbers");
   scanf("%d",&n);
   if(n>30)
    {
      printf("\n Too many Numbers");
      exit(0); 
    }
   printf("\n Enter the array elements \n");
   for(i=0 ; i< n; i++)
   scanf("%d", &a[i]);                                       // Step 1
   for(i = 0; i < n-1 && sorted==0; i++)                     // Step 2
   {
     sorted=1;                                         
     for(j = 0; j < (n - i) -1; j++)                        // Step 3
      if(a[j] > a[j+1])                                     
       {
         temp = a[j];                                       // Step 4
          a[j] = a[j+1];
          a[j+1] = temp;
          sorted=0;
       }
    }
    printf("\n The numbers in sorted order \n");            // Step 5
    for(i=0; i < n; ++i)
    printf("\n %d", a[i]);
   return 0;
}


edit-code-image

Sample test cases:

1. How many numbers : 5
Enter the array elements
34
89
1
0
45

The numbers in sorted order
0
1
34
45
89

2. How many numbers : 3
Enter the array elements
1
2
1
The numbers in sorted order
1
1
2

Explanation to sort array elements:

Step 1: The elements are read into an array from the user using scanf() function.
Step 2: The outer for loop make sure that by the end of it all the elements are sorted.
Step 3: The inner for loop takes two adjacent elements and compares them and swaps if they are not in sorting order.By the end of one inner loop the largest number will be moved to the top of array.
Step 4: The two adjacent elements are swapped if they are not in increasing order.
Step 5 : The elements in array are sorted by the end of outer for loop which are displayed on output screen using for loop. This is the way to sort array elements.

Explore C Programs:C Programs
More about Sort Array:More Information