Q:

Java program to sort a one dimensional array in ascending order

belongs to collection: Java Array Programs

0

Given an array and we have to sort its elements in ascending order and print the sorted array using java program.

Example:

    Input:
    Array (elements will be read in program): 25 54 36 12 48 88 78 95 54 55
    Output:
    Sorted List in Ascending Order : 
    12  25  36  48  54  54  55  78  88  95  

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to sort an array in ascending order in java

import java.util.Scanner;

public class ExArraySort {
  public static void main(String args[]) {
    // initialize the objects.
    int n, i, j, temp;
    int arr[] = new int[50];
    Scanner scan = new Scanner(System.in);

    // enter number of elements to enter.
    System.out.print("Enter number for the array elements : ");
    n = scan.nextInt();

    // enter elements.
    System.out.println("Enter " + n + " Numbers : ");
    for (i = 0; i < n; i++) {
      arr[i] = scan.nextInt();
    }

    // sorting array elements.
    System.out.print("Sorting array : \n");
    for (i = 0; i < (n - 1); i++) {
      for (j = 0; j < (n - i - 1); j++) {
        if (arr[j] > arr[j + 1]) {
          temp = arr[j];
          arr[j] = arr[j + 1];
          arr[j + 1] = temp;
        }
      }
    }

    System.out.print("Array Sorted Successfully..!!\n");

    // array in ascending order.
    System.out.print("Sorted List in Ascending Order : \n");
    for (i = 0; i < n; i++) {
      System.out.print(arr[i] + "  ");
    }
  }
}

Output

Enter number for the array elements : 10
Enter 10 Numbers : 
25
54
36
12
48
88
78
95
54
55
Sorting array : 
Array Sorted Successfully..!!
Sorted List in Ascending Order : 
12  25  36  48  54  54  55  78  88  95  

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Array Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to read and print a two dimensional a... >>
<< Java program to merge two one dimensional arrays...