// Sort an Array of Integer and Floats in Ascending or Descending order
import java.io.*;
import java.text.DecimalFormat;
public class SortArray
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter Total Number of Elements:: ");
int n = Integer.parseInt(br.readLine());
float[] a = new float[n];
int i, j;
// Read Array Elements from User
for (i = 0; i < a.length; i++)
{
System.out.print("Enter Element:: ");
a[i] = Float.parseFloat(br.readLine());
}
// Sorting Array Elements
for (i = 0; i < a.length; i++)
for (j = 0; j < a.length - i - 1; j++)
if (a[j] > a[j + 1]) // For Ascending use '>' greater than sign
// For Descending use '<' less than sign
{
// Swapping without using temporary variable
a[j] = a[j] + a[j + 1];
a[j + 1] = a[j] - a[j + 1];
a[j] = a[j] - a[j + 1];
}
// Displaying Sorted Array
System.out.println("\nSorted Array is::");
for (i = 0; i < a.length; i++)
{
// Displaying only single value after decimal point
// by using 'DecimalFormat'
System.out.println(new DecimalFormat("##.#").format(a[i]));
}
}
}
import java.io.*;
import java.text.DecimalFormat;
public class SortArray
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter Total Number of Elements:: ");
int n = Integer.parseInt(br.readLine());
float[] a = new float[n];
int i, j;
// Read Array Elements from User
for (i = 0; i < a.length; i++)
{
System.out.print("Enter Element:: ");
a[i] = Float.parseFloat(br.readLine());
}
// Sorting Array Elements
for (i = 0; i < a.length; i++)
for (j = 0; j < a.length - i - 1; j++)
if (a[j] > a[j + 1]) // For Ascending use '>' greater than sign
// For Descending use '<' less than sign
{
// Swapping without using temporary variable
a[j] = a[j] + a[j + 1];
a[j + 1] = a[j] - a[j + 1];
a[j] = a[j] - a[j + 1];
}
// Displaying Sorted Array
System.out.println("\nSorted Array is::");
for (i = 0; i < a.length; i++)
{
// Displaying only single value after decimal point
// by using 'DecimalFormat'
System.out.println(new DecimalFormat("##.#").format(a[i]));
}
}
}
OUTPUT::
Enter Total Number of Elements:: 4
Enter Element:: 6.7
Enter Element:: 2.3
Enter Element:: 5.9
Enter Element:: 2.8
Sorted Array is::
2.3
2.8
5.9
6.7