Write the program in java to sort an array ?
package pkg;
import java.util.*;
public class S {
public static void main(String[] args) {
// TODO Auto-generated method stub
int n, temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter the elements:");
for (int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.print("Sorting an array:");
for (int i = 0; i < n - 1; i++)
{
System.out.print(a[i] + ",");
}
System.out.print(a[n - 1]);
}
}
Output:-
Enter no. of elements:5
Enter the elements:
4 9 3 15 7 2
Sorting an array:3,4,7,9,15
import java.util.*;
public class S {
// TODO Auto-generated method stub
int n, temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter the elements:");
for (int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.print("Sorting an array:");
for (int i = 0; i < n - 1; i++)
{
System.out.print(a[i] + ",");
}
System.out.print(a[n - 1]);
}
}
Enter no. of elements:5
Enter the elements:
4 9 3 15 7 2
Sorting an array:3,4,7,9,15