C++ | Sorting The Elements in Array

Introduction

This is a tutorial for sorting the elements in array in ascending or descending order. The program is given below that takes the array from user, sorts it and prints the sorted array. The program is extendable. Go enjoy the program. Lets begin….

Program for sorting the elements in array.

#include<iostream.h>
#include<conio.h>
void main()
{
//clear the screen.
clrscr();
//declare variable type int
int a[10],i,j,temp,n = 5;
//Input the two numbers save them in arrays.
for(i=0;i<n;i++)
{
cout<<"Enter the no :";
cin>>a[i];
}
//sort the array
for(i=0;i<n-1;i++)
{
  for(j=0;j<n-i-1;j++)
  {
    if(a[i]<a[j])
    {
     temp = a[i];
     a[i] = a[j];
     a[j] = temp;
    }
  }
}
//Print the array.
for(i=0;i<n;i++)
cout<<a[i]<<endl;
//get character
getch();
}

Output

Enter the no : 2
Enter the no : 3
Enter the no : 1
Enter the no : 5
Enter the no : 4
1
2
3
4
5

How does it work.

  1. You enter the number in array.
  2. The numbers are sorted.
  3. The sorted array is printed.

Extending it.

The program is extendable as you wish or your requirement. Or you can make the same program for arranging the elements in descending order by just changing the sign in program at the if(a[i]<a[j]) statement in program.

Explanation.

  1. Include ‘iostream.h’ and ‘conio.h’ files.
  2. Add void main.
  3. Start program by first clearing the screen.
  4. Declare variables and array.
  5. Add cout and cin to get array.
  6. Search the array.
  7. Print the sorted array.
  8. Get character.

At the end

You learnt creating the C++ program for Sorting a element in array. So now enjoy the program.

Please  share it.

Join India's Largest Code Learning Community on Uphub.io Get it on Google Play
Sharing options: