×

Java Programs

Java Practice

Java program to sort a one dimensional array in ascending order

Here, we are implementing a java program to sort an array (one-dimensional array) in ascending order? We are reading array elements, arranging them in ascending order and printing the sorted array. By IncludeHelp Last updated : December 23, 2023

Problem statement

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  

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  

Java Array Programs »

More Java Array Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.