Write C++ program to sort array in ascending order

c++

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: 

                          c++_1

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:

                                  c++_2

 

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:

                                  c++_3

 

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

Example code:

                                    c++_4

 

 

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

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

Program:

Output:

sort

 

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

About the Author: thecoder

3 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *