# Write C++ program to sort array in ascending order

hello, friends in today’s article I am going to share C++ program to sort array in ascending order so let’s begin today’s article

**so first, we have to understand what is sorting?**

sorting means the process of arranging items in a specific order.

**next, What do you mean by ascending order?**

ascending order means an arrangement of items from smallest to largest.

## Explanation

There is various logic to sort given set of numbers. Here I am using a general algorithm which we apply in real life for simplicity.

In this program, we need to sort the given array in ascending order such that elements will be arranged from smallest to largest. This can be achieved through two loops. The outer loop will select an element, and the inner loop allows us to compare the selected element with the rest of the elements.

**Example:**

** Original array: **3 2 1 6 4

** Array after sorting: **1 2 3 4 6

now,

## You May also like: python program to perform addition subtraction multiplication and division

## Logic to sort array in ascending order

**Step 1:** Take the input size of the array and elements. stored it in the variable say size, n.

*Example code:*

**Step 2:** use one for loop as an outer for loop to select each element from an array, starting from 0 up to the size of the array.

**Example code:**

** **

**Step 3:** use another inner for loop to compare the selected element from the outer loop with the rest of the elements of the array.

**Example code:**

** **

**Step 4:** If any element is less than the selected element then swap the values as follows:

**Example code:**

** **

so finally the program is completed, check the below code:

## You May also like: nptel online courses (Free Courses Updated)

## Program:

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 39 40 41 42 | #include <iostream> #define MAX_SIZE 100 using namespace std; int main() { int i,a[MAX_SIZE],temp,j,size; cout<<"Enter size of array: \n"; cin>>size; cout<<"Enter numbers in array: \n"; for(i=0;i<size;i++) { cin>>a[i]; } cout<<"\nData before sorting: "; for(j=0;j<size;j++) { cout<<a[j]; } for(i=0;i<size;i++) { for(j=0;j<=size-i-1;j++) { if(a[j]>a[j+1]) { temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } cout<<"\nData after sorting: "; for(j=0;j<size;j++) { cout<<a[j]; } return 0; } |

## Output:

thank you for reading this article, if you like our article please share with your friends, and if you have any queries related to program comment below we will definitely reply

## 3 Comments