Java program for Sorting Elements In An Array

Sorting Elements in an Array using Java

Here on this page, we will discuss Sorting Elements in an array using Java Programming Language with different types of Sorting Techniques.

Whereas, Sorting is a fundamental operation in computer science and programming. In Java, sorting an array can be done using various algorithms, each with its own performance characteristics. This article covers multiple sorting methods in Java with complete code examples, theoretical explanations, and complexity analysis.

Sorting element in array by frequency using C++

This problem statement can be resolved by following sorting techniques….

Methods of Sorting Elements in an Array

We will cover the following techniques:

  1. Bubble Sort
  2. Selection Sort
  3. Insertion Sort
  4. Arrays.sort() (Built-in Java utility)
  5. Merge Sort
  6. Quick Sort

1. Bubble Sort Technique for Sorting Elements

Algorithm:

  1. Iterate over the array multiple times.
  2. In each iteration, compare adjacent elements and swap them if they are in the wrong order.
  3. Continue the process until the array is fully sorted.

Code:

Run

public class BubbleSort {
    public static void bubbleSort(int[] arr) {
        int n = arr.length;
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }

    public static void main(String[] args) {
        int[] array = {5, 2, 9, 1, 5, 6};
        bubbleSort(array);
        for (int num : array) {
            System.out.print(num + " ");
        }
    }
}

Output:

1 2 5 5 6 9

2. Selection Sort Technique for Sorting Elements

Algorithm:

  1. Traverse the array to find the smallest element.

  2. Swap it with the element at the beginning.

  3. Move the boundary of the sorted subarray one element forward.

  4. Repeat until the entire array is sorted.

Code:

Run
public class SelectionSort {
    public static void selectionSort(int[] arr) {
        int n = arr.length;
        for (int i = 0; i < n - 1; i++) {
            int minIndex = i;
            for (int j = i + 1; j < n; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }
            int temp = arr[i];
            arr[i] = arr[minIndex];
            arr[minIndex] = temp;
        }
    }

    public static void main(String[] args) {
        int[] array = {29, 10, 14, 37, 13};
        selectionSort(array);
        for (int num : array) {
            System.out.print(num + " ");
        }
    }
}

Output:

10 13 14 29 37

Prime Course Trailer

Related Banner

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

3. Insertion Sort Technique for Sorting

Algorithm:

  1. Start from the second element.
  2. Compare the current element with its predecessors.
  3. Shift the elements that are greater than the current element.
  4. Insert the current element at its correct position.

Code:

Run

public class InsertionSort {
    public static void insertionSort(int[] arr) {
        for (int i = 1; i < arr.length; i++) { int key = arr[i]; int j = i - 1; while (j >= 0 && arr[j] > key) {
                arr[j + 1] = arr[j];
                j--;
            }
            arr[j + 1] = key;
        }
    }

    public static void main(String[] args) {
        int[] array = {12, 11, 13, 5, 6};
        insertionSort(array);
        for (int num : array) {
            System.out.print(num + " ");
        }
    }
}

Output:

5 6 11 12 13

4. Arrays.sort(): Built in Method

Algorithm:

This method uses a Dual Pivot Quicksort for primitive types, offering excellent performance.

Code:

Run
import java.util.Arrays;

public class BuiltInSort {
    public static void main(String[] args) {
        int[] array = {7, 3, 9, 2, 8};
        Arrays.sort(array);
        for (int num : array) {
            System.out.print(num + " ");
        }
    }
}

Output:

2 3 7 8 9

5. Merge Sort for Sorting elements

Algorithm:

  1. Divide the array into two halves.
  2. Recursively sort both halves.
  3. Merge the sorted halves.

Code:

Run
public class MergeSort {
    public static void mergeSort(int[] arr, int left, int right) {
        if (left < right) {
            int mid = (left + right) / 2;
            mergeSort(arr, left, mid);
            mergeSort(arr, mid + 1, right);
            merge(arr, left, mid, right);
        }
    }

    public static void merge(int[] arr, int left, int mid, int right) {
        int n1 = mid - left + 1;
        int n2 = right - mid;
        int[] L = new int[n1];
        int[] R = new int[n2];

        for (int i = 0; i < n1; i++) L[i] = arr[left + i];
        for (int j = 0; j < n2; j++) R[j] = arr[mid + 1 + j];

        int i = 0, j = 0, k = left;
        while (i < n1 && j < n2) {
            if (L[i] <= R[j]) arr[k++] = L[i++];
            else arr[k++] = R[j++];
        }
        while (i < n1) arr[k++] = L[i++];
        while (j < n2) arr[k++] = R[j++];
    }

    public static void main(String[] args) {
        int[] array = {12, 11, 13, 5, 6, 7};
        mergeSort(array, 0, array.length - 1);
        for (int num : array) {
            System.out.print(num + " ");
        }
    }
}

Output:

5 6 7 11 12 13

6. Quick Sort for Sorting elements

Algorithm:

  1. Select a pivot element.
  2. Partition the array around the pivot such that left side has smaller and right side has greater elements.
  3. Recursively apply the above steps to the subarrays.

Code:

Run

public class QuickSort {
    public static void quickSort(int[] arr, int low, int high) {
        if (low < high) {
            int pi = partition(arr, low, high);
            quickSort(arr, low, pi - 1);
            quickSort(arr, pi + 1, high);
        }
    }

    public static int partition(int[] arr, int low, int high) {
        int pivot = arr[high];
        int i = low - 1;
        for (int j = low; j < high; j++) {
            if (arr[j] < pivot) {
                i++;
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
        int temp = arr[i + 1];
        arr[i + 1] = arr[high];
        arr[high] = temp;
        return i + 1;
    }

    public static void main(String[] args) {
        int[] array = {10, 7, 8, 9, 1, 5};
        quickSort(array, 0, array.length - 1);
        for (int num : array) {
            System.out.print(num + " ");
        }
    }
}

Output:

1 5 7 8 9 10

FAQ's related to Sorting Elements

Answer:

For small datasets, Insertion Sort or Bubble Sort is often sufficient and performs well due to low overhead and simple implementation.

Answer:

Merge Sort, Quick Sort, and Heap Sort all have an average-case time complexity of O(n log n), making them efficient for most practical use cases.

Answer:

Yes, Arrays.sort() is optimized:

  • For primitive types, it uses a Dual Pivot QuickSort.
  • For objects, it uses TimSort, a hybrid of Merge Sort and Insertion Sort.

Answer:

Yes, you can sort in descending order by:

  1. Sorting normally and then reversing the array.
  2. Or using Arrays.sort(array, Collections.reverseOrder()) for object arrays.

Answer:

  1. Stable sort maintains the relative order of equal elements (e.g., Merge Sort, Bubble Sort).
  2. Unstable sort does not guarantee relative ordering (e.g., Quick Sort, Heap Sort).

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription

7 comments on “Java program for Sorting Elements In An Array”


  • sagarbeura1234

    public class Sort_Element_Of_Array {
    public static void main(String[] args) {
    int arr[] = {98,34,56,13,45,32,54,76};

    TreeSet ts = new TreeSet();

    for(Object obj : arr) {
    ts.add((Integer)obj);
    }
    System.out.println(“After Sorting : “+ts);
    }
    }


  • Khushi Saxena

    import java.util.*;
    class HelloWorld {
    public static void main(String[] args) {
    int a[]={5,9,3,8,4};
    int n=a.length;
    Arrays.sort(a);
    for(int i=0;i<n;i++){
    System.out.println(a[i]);
    }
    }
    }
    Time Complexity: O(nlogn)


  • Gyanendra

    import java.util.*;
    public class Main{
    public static void main(String[] args){
    Scanner scn=new Scanner(System.in);
    int n=scn.nextInt();
    int[] arr=new int[n];

    for(int i=0;i<n;i++){
    arr[i]=scn.nextInt();
    }

    for(int i=0;i<n-1;i++){

    int temp=0;
    for(int j=i+1;jarr[j]){
    int val=arr[i];
    arr[i]=arr[j];
    arr[j]=val;
    temp=1;
    }
    }

    if(temp==0){
    break;
    }
    }

    for(int val:arr){
    System.out.print(val+” “);
    }
    }
    }


  • bhondaverupesh0

    Method3=Parallel sort Approach
    package Sort_Array;
    import java.util.*;

    public class Sort_Array_Using_Inbuilt_Method
    {
    public static void main(String[]args)
    {
    Scanner sc=new Scanner(System.in);
    System.out.println(“Enter size of array “);
    int n=sc.nextInt();
    int []a=new int[n];

    System.out.println(“Enter element in array “);
    for(int i=0;i<a.length;i++)
    {
    a[i]=sc.nextInt();
    }

    Arrays.parallelSort(a);
    System.out.println(Arrays.toString(a));
    }
    }


  • bhondaverupesh0

    // Rupesh Bhondave @Mumbai

    ackage Sort_Array;
    import java.util.*;

    public class Sort_Using_Navie_Approch
    {
    public static void main (String[]args)
    {
    Scanner sc=new Scanner(System.in);
    System.out.println(“Enter size of array “);
    int n=sc.nextInt();
    int []a=new int[n];

    System.out.println(“Enter element of array “);
    for(int i=0;i<a.length;i++)
    {
    a[i]=sc.nextInt();
    }

    int temp=0;
    for(int i=0;i<a.length;i++)//first loop start element from o
    {
    for(int j=i+1;ja[j])// i is greater than j then swap elements
    {
    temp=a[i];
    a[i]=a[j];
    a[j]=temp;
    }
    }

    }
    for(int i=0;i<a.length;i++)
    {
    System.out.print(a[i]+" ");
    }
    }
    }


  • Pranjal

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

    public class BubbleSort {
    public static void main(String[] args){
    Scanner s = new Scanner(System.in);
    System.out.println(“Enter the number of elements you want to enter:”);
    int n = s.nextInt();
    int[] arr = new int[n];

    System.out.println(“Enter the elements: “);
    for (int i = 0; i < n; i++) {
    arr[i] = s.nextInt();
    }
    System.out.println("The number you entered: " + Arrays.toString(arr));
    for (int i=0; i< arr.length; i++)
    {
    for (int j =0; jarr[j+1])
    {
    int temp= arr[j];
    arr[j]= arr[j+1];
    arr[j+1]=temp;
    }
    }
    }
    System.out.println(” The sorted array is” +Arrays.toString(arr));
    }
    }


  • Durai

    package com.javabasic;
    import java.util.Scanner;
    public class Main {
    public static void prep(int[] a, int total){
    int temp;
    for (int i = 0; i < total; i++)
    {
    for (int j = i + 1; j a[j])
    {
    temp = a[i];
    a[i] = a[j];
    a[j] = temp;
    }
    }
    }
    for (int i=0;i<total;i++) {
    System.out.println(a[i]);
    }
    }
    public static void main(String[] args) {
    int []a=new int[50];
    var sc=new Scanner(System.in);
    System.out.println("Enter Array Size : ");
    int size=sc.nextInt();
    System.out.println("Enter the elements one by one ");
    for (int i=0;i<size;i++) {
    a[i]=sc.nextInt();
    }
    prep(a,size);
    }
    }

    This is a correct program