## 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 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.

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.

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 |
public class sortAsc { public static void main(String []args) throws IOException{ int n,i,j,t; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter the number of values you want to compare: "); n = Integer.parseInt(br.readLine()); int[] arr = new int[n]; System.out.print("Enter "+ n +" numbers one by one: "); for(i=0;i<n;i++){ arr[i] = Integer.parseInt(br.readLine()); } for(i=0;i<n-1;i++){ for(j=i+1;j<n;j++){ if(arr[i] > arr[j]){ t=arr[i]; arr[i]=arr[j]; arr[j]=t; } } } System.out.println("The sorted numbers are: "); for(i=0;i<n;i++){ System.out.println(arr[i]); } } } |

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
Enter the number of values you want to compare: 8 Enter 8 numbers one by one: 10 15 11 13 17 16 14 12 The sorted numbers are: 10 11 12 13 14 15 16 17 |