Question
Write a program to sort an array in ascending order.
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
import java.util.Scanner;
public class sortArrayInAsc
{
public static void main(String[] args)
{
/* Initialize array */
int [] arr1;
int n=0,i=0,j=0,temp=0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a no. of elements in the array");
n = sc.nextInt();
System.out.println("Enter numbers in array");
arr1=new int[n];
for(i=0;i< n;i++)
{
arr1[i]=sc.nextInt();
}
System.out.println("Elements of original array: ");
for (i = 0; i < n; i++)
{
System.out.print(arr1[i] + " ");
}
/* sorting of array in ascending order is done here */
for (i = 0; i < n; i++)
{
for (j = i+1; j < n; j++)
{
if(arr1[i] > arr1[j])
{
temp = arr1[i];
arr1[i] = arr1[j];
arr1[j] = temp;
}
}
}
System.out.println();
/* Sorted array */
System.out.println("Elements of array in ascending order: ");
for (i = 0; i < n; i++)
{
System.out.print(arr1[i] + " ");
}
}
}