Sort numbers in ascending order – Java Program


Sort array values in ascending order using Bubble Sort

Sorting is an operation of arranging values in a systematic order. It may be in ascending order or in descending order.

Here in this program, we are going to sort the values in ascending order.


What we are going to do

What it is going to do is, it is going to ask the number of values the user wants to enter and depending on the number, it is going to ask ‘n’ numbers from the user. After taking user input, our program will compare the ‘n’ number of values entered by the user and sort it in ascending order.

For example – The user enters the number of values to be 8. Then after hitting enter, the program will ask 8 numbers from the user.

So if the input numbers are 10 15 11 13 17 16 14 12. The output will be  10 11 12 13 14 15 16 17.

How we are going to do it

Here we will be using an array to store the user values. Where one value will be assigned to one index of the array.

To sort the values we need for loops and if statement. Now the plan is to compare each element of the array with its adjacent element. So what it is going to do is, compare the first value with the second value. If the first value is greater than the second value, then swap the two values. Now the first value becomes smaller than the second one.

Move to the next step. Compare second value with the third value. If the second value is less than the third one, do nothing. Move to the next step. This process continues until all the values are sorted in ascending order. This process is also known as Bubble Sort.


You May Also Like

Leave a Reply

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