Program to sort an array in Java

 



Code:

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        int n;
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the size of array: ");
        n = sc.nextInt();
        int a[] = new int[n];
        for (int i = 0; i < a.length; i++) {
            System.out.print("Enter " + (i + 1) + " element: ");
            a[i] = sc.nextInt();
        }
        int temp;
        for (int j = 0; j < a.length; j++) {
            for (int d = j + 1; d < a.length; d++) {
                if (a[j] > a[d]) {
                    temp = a[j];
                    a[j] = a[d];
                    a[d] = temp;
                }
            }
        }

        System.out.println("\nSorted array:");
        for (int c = 0; c < a.length; c++) {
            System.out.println("a[" + c + "]=" + a[c]);
        }
    }
}


Output:

AJ Blogs

Hello everyone, My name Arth and I like to write about what I learn. Follow My Website - https://sites.google.com/view/aj-blogs/home

Post a Comment

Previous Post Next Post
Best Programming Books

Facebook

AJ Facebook
Checkout Our Facebook Page
AJ Blogs
Checkout Our Instagram Page