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 April 19, 2024 by Abhishek Sharma

Sorting elements in an array is a common operation in programming. Java provides several built-in methods and algorithms for sorting arrays efficiently. In this article, we’ll explore how to write a Java program to sort elements in an array using different sorting algorithms, such as bubble sort, selection sort, insertion sort, and the built-in Arrays.sort() method.

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
Sorting elements in an array is a fundamental operation in programming, and Java provides several efficient methods and algorithms for sorting arrays. Whether you use the simple bubble sort, selection sort, insertion sort, or the built-in Arrays.sort() method, understanding these sorting algorithms is essential for writing efficient and reliable Java programs.

Frequently asked Questions related to Arrays in Java

Below are some of the FAQs related to Java Program for Sorting Elements in an Array:

1. Can I use the Arrays.sort() method to sort arrays of any data type in Java?
Yes, the Arrays.sort() method can be used to sort arrays of any data type, including primitive types (such as int, float, char, etc.) and objects (such as String, Integer, etc.), as long as the data type implements the Comparable interface.

2. Which sorting algorithm is the most efficient in Java?
The most efficient sorting algorithm in Java depends on the size of the array and the distribution of elements. Generally, the dual-pivot Quicksort algorithm used by the Arrays.sort() method is efficient for most cases.

3. How can I sort an array in descending order in Java?
You can sort an array in descending order by using the Arrays.sort() method and then reversing the sorted array using Collections.reverseOrder().

4. Are there any sorting algorithms in Java that work better for nearly sorted arrays?
Yes, algorithms like Insertion Sort and Adaptive Sorting Algorithms (such as Timsort used in Arrays.sort()) are more efficient for nearly sorted arrays compared to other sorting algorithms.

5. Can I use the Arrays.sort() method to sort a two-dimensional array in Java?
Yes, you can use the Arrays.sort() method to sort a two-dimensional array in Java. You need to specify the comparator for the sorting order (e.g., row-wise or column-wise).

Leave a Reply

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