Sunday, 11 October 2015

Java program to sort numbers in ascending order

Requirement: I want to pass numbers randomly from the console and want to sort those inserted numbers in ascending order.

Solution: The Java code for the above requirement is shown below:

Program:

package com.susanto;

import java.util.Scanner;

public class SortingNumbers {
      public static void main(String[] args) {
            int n, temp;
            Scanner s = new Scanner(System.in);
            System.out.print("Enter number of elements :");
            n = s.nextInt();
            int a[] = new int[n];
            System.out.println("Enter all the elements:");
            for (int i = 0; i < n; i++) {
                  a[i] = s.nextInt();
            }
            for (int i = 0; i < n; i++) {
                  for (int j = i + 1; j < n; j++) {
                        if (a[i] > a[j]) {
                              temp = a[i];
                              a[i] = a[j];
                              a[j] = temp;
                        }
                  }
            }
            System.out.print("Ascending Order:");
            for (int i = 0; i < n - 1; i++) {
                  System.out.print(a[i] + ",");
            }
            System.out.print(a[n - 1]);
      }
}


Output:

Enter number of elements :7
Enter all the elements:
6
1
6
4
90
44
2
Ascending Order:1,2,4,6,6,44,90


Hence, the solution to our requirement.


Thanks & Regards,
Susanto Paul