JAVA PROGRAM
Program to sort a set of numbers using class | Java Program |
Introduction
Sorting numbers is a fundamental task in programming, and Java provides a straightforward way to accomplish this. In this blog post, we will explore a simple Java program that sorts a set of numbers in ascending order. This program uses basic concepts like arrays and loops to perform the sorting operation.
Code
import java.io.*;
class Sort {
public static void main(String args[]) throws IOException {
DataInputStream s = new DataInputStream(System.in);
System.out.println("Enter the number of elements:");
int n = Integer.parseInt(s.readLine());
System.out.println("Enter the elements:");
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(s.readLine());
}
// Sorting the array using a simple sorting algorithm (Bubble Sort)
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i] > a[j]) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.println("The sorted elements are:");
for (int i = 0; i < n; i++) {
System.out.println(a[i]);
}
}
}
Output
Enter the number of elements:
5
Enter the elements:
5
4
3
2
1
The sorted elements are:
1
2
3
4
5
Explanation
1. Input Handling:
The DataInputStream class is used to read the input from the console. The number of elements (n) is read first, followed by the elements themselves, which are stored in an array a.
2. Sorting Logic:
A nested loop structure is used for sorting. The outer loop iterates through each element, while the inner loop compares the current element with the subsequent elements.
If a pair of elements are out of order, they are swapped. This is a basic implementation of the Bubble Sort algorithm.
3. Output:
After sorting, the elements are printed in ascending order.
Conclusion
This simple Java program demonstrates how to sort a set of numbers using an array and a basic sorting algorithm. Understanding and implementing such basic algorithms is crucial for learning more complex sorting techniques and algorithms in the future. This foundational knowledge will also help in optimizing and writing more efficient code for larger datasets.
Post a Comment
0 Comments