Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Java Program for Sorting Elements in an Array

Last Updated on May 17, 2023 by Prepbytes

In order to organize the components in this program from smallest to largest, we must sort the provided array in ascending order. Two loops can be used to accomplish this. An element will be chosen by the outer loop, and we may compare it to the other items using the inner loop.

The order of the elements will be such that the smallest element, in this example 1, which is the smallest, will appear on the far left. On the far right, the greatest piece, in this case, 8 will be visible.

Input:

Enter the Array Elements: 5 4 6 7 8 2 3 1 9

Output:

The Sorted Array in Ascending Order: 1 2 3 4 5 6 7 8 9

Approaches for Sorting Elements in an Array in Java

Below are two approaches

  • Approach 1: Using Loops
  • Approach 2: Using Arrays.sort()

Let us look at each of these methods separately.

Program 1: Sort the Elements of an Array in Ascending Order

This method demonstrates how to sort an array in ascending order using loops. The array may be manually sorted using techniques like for loops. We may achieve this by employing two for loops: one to iterate over the array starting at the beginning, and a second for loop within the outer one to go through the subsequent element. If the neighboring items in the body are out of order, we can swap them out by comparing them. To switch items, we may alternatively utilize a temporary variable.

Algorithm for Sort the Elements of an Array in Ascending Order

  1. Start
  2. Declare an array
  3. Ask the user to initialize the array
  4. Declare a temporary variable to store the elements while swapping.
  5. Use two for loops for the same.
  6. Use the first for loop to hold the elements and traverse through all the elements.
  7. Use the second for loop to compare with the remaining elements.
  8. Sort the elements by comparing and swapping.
  9. Display the updated array.
  10. Stop

Code Implementation:

/*Java Program to Sort an Array in Ascending Order*/
import java.util.Arrays;
import java.util.Scanner;
import java.util.Collections;

public class Main
{
    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);
        int n;    //Array Size Declaration
        System.out.println("Enter the number of elements :");
        n=sc.nextInt();    //Array Size Initialization
        
        Integer arr[]=new Integer[n];    //Array Declaration
        System.out.println("Enter the elements of the array :");
        for(int i=0;i<n;i++)     //Array Initialization
        {
            arr[i]=sc.nextInt();
        }
        
        int temp = 0;    //Temporary variable to store the element
        
         for (int i = 0; i < arr.length; i++)   //Holds each Array element
         {     
            for (int j = i+1; j < arr.length; j++)    //compares with remaining Array elements
            {     
               if(arr[i] > arr[j]) //Compare and swap
               {    
                   temp = arr[i];    
                   arr[i] = arr[j];    
                   arr[j] = temp;    
               }     
            }     
        }    
          
        System.out.println();    
            
        //Displaying elements of array after sorting    
        System.out.println("Elements of array sorted in ascending order: ");    
        for (int i = 0; i < arr.length; i++) 
        {     
            System.out.print(arr[i] + " ");    
        }    
    }
}

Input:

Enter the number of elements: 5
Enter the elements of the array: 7 2 6 5 3

Output:

Sorted arr[] : [2, 3, 5, 6, 7]

Program 2: Sort the Elements of an Array in Ascending Order

This method demonstrates how to sort an array in ascending order using Arrays.sort(). The sort function, which accepts an array as an input and sorts the array, is offered by the Arrays class of the ‘java.util’ package. With just one method call, the array may be sorted in ascending order using this direct sorting approach.

Algorithm to Sort the Elements of an Array in Ascending Order

  1. Start
  2. Declare an array
  3. Ask the user to initialize the array
  4. Use the Arrays.sort() to sort the elements in ascending order.
  5. Print the updated array.
  6. Stop

Code Implementation:

/*Java Program to Sort an Array in Ascending Order*/

import java.util.Arrays;
import java.util.Scanner;

class AscendingOrder
{
    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);
        int n;    //Array Size Declaration
        System.out.println("Enter the number of elements :");
        n=sc.nextInt();    //Array Size Initialization
        
        int arr[]=new int[n];    //Array Declaration
        System.out.println("Enter the elements of the array :");
        for(int i=0;i<n;i++)     //Array Initialization
        {
            arr[i]=sc.nextInt();
        }
        
        Arrays.sort(arr);    //Sorts the Array in Ascending Order
 
        System.out.printf("Sorted arr[] : %s",
                          Arrays.toString(arr));   //Prints the sorted Array
    }
}

Input:

Enter the number of elements: 5
Enter the elements of the array: 20 12 60 54 30

Output:

Sorted arr[] : [12, 20, 30, 54, 60]

Conclusion
This article taught you the methods to sort an array in ascending order in Java. we hope this blog gives you a prior understanding of the array in Java. Many companies like TCS, Wipro, Infosys, Cognizant, and many more ask about the array in their technical interviews.

Frequently asked Questions related to Arrays in Java

Q1. How many types of sorting are there in Java?
Ans. In Java, there are 5 popular sorting algorithms i.e.

  • Merge Sort
  • Heap Sort
  • Insertion Sort
  • Selection Sort
  • Bubble Sort

Q2. How can I sort an array in Java?
Ans. In Java, you can sort an array using the Arrays.sort() method from the java.util

package. Here's an example:
import java.util.Arrays;

public class ArraySortingExample {
    public static void main(String[] args) {
        int[] array = {5, 2, 9, 1, 3};

        // Sort the array in ascending order
        Arrays.sort(array);

        // Print the sorted array
        System.out.println(Arrays.toString(array));
    }
}

Q3. Can I sort an array of objects in Java?
Ans. Yes, you can sort an array of objects in Java. However, for the sorting to work correctly, the objects must implement the Comparable interface, which defines the natural ordering of the objects. Alternatively, you can provide a custom Comparator to specify the sorting logic.

Q4. How can I sort an array in descending order?
Ans. By default, the Arrays.sort() method sorts the array in ascending order. If you want to sort the array in descending order, you can either reverse the array after sorting or provide a custom Comparator that defines the descending order.

Leave a Reply

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