In this tutorial you will learn about the C++ Programs to Sort Array Element and its application with practical example.
In this tutorial, we will learn to create a C++ program that will sort Array Elements using C++ programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C++ programming topics:
- Operators.
- looping statements.
- Basic input/output.
- Basic c++ programming
- For Loop.
- Array.
What is array?
An Array is a collection variable elements that can store multiple values in a single variable of same type.In Computer Science,an array is a data structure, or simply an array, is a data structure consisting of a collection of elements.
C++ Programs to Sort Array Element.
In this program we will sort Array elements. We would first declared and initialized the required variables. then we would prompt user to input elements of array .Later we sort an Array elements in ascending order.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
#include <iostream> using namespace std; int main() { int a[100],num, i, j, tmp; // declaring variables // Reading the size of the array cout<<"Enter size of an array: "; //taking the size of array cin>>num; //Reading elements of array cout<<"Enter elements in an array: "; // getting elements of array for(i=0; i<num; i++) { cin>>a[i]; } for(i=0; i<num; i++) //Sorting an array in ascending order { for(j=i+1; j<num; j++) { if(a[j] < a[i]) { tmp = a[i]; a[i] = a[j]; a[j] = tmp; } } } cout<<"Elements of array in sorted ascending order:"<<endl; for(i=0; i<num; i++) { cout<<a[i]<<" " ; } return 0; } |
Output
In the above program, we have first declared and initialized a set variables required in the program.
- a[] = it will hold entered elements.
- num =it will hold size of array.
- i and j= for iteration.
- tmp= it hold temporary values.
In our program, we will take 5 values form user in an array , after taking these values we will sort the elements of an array.
First of all we take size of an array from user in variable num.
After taking size of an array user will prompted to enter the elements of array.
Here we will use selection sort algorithm sorts an array by repeatedly finding the minimum element from unsorted part and putting it at the beginning.
In every iteration sorted value is arranging in a[i] .At the end the value of sorted array will be printed.