This is a very simple sorting logic that I have written and it's working also. But Is there anything wrong in the traversing of the array? Or the code is not optimized? The code is simply declaring an array of size N. And then sorting is performed by traversing.
import java.util.Scanner;
import java.io.*;
class BubbleSort
{
public static void main(String args[])throws IOException
{
int size,temp=0;
System.out.println("Enter the size of the array");
Scanner sc=new Scanner(System.in);
size=sc.nextInt();
int arr[]=new int[size];
System.out.println("Enter the elements in the array");
for(int i=0;i<size;i++)
{
arr[i]=sc.nextInt();
}
for(int i=0;i<size;i++) //Here is the sorting logic
{
for(int j=i+1;j<size;j++)
{
if(arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
for(int i=0;i<size;i++)
{
System.out.print(arr[i]);
}
}
}
-
\$\begingroup\$ You're using Bubble Sort, there are multiple algorithms to sort an array. You can go through them \$\endgroup\$Nicholas K– Nicholas K2018年10月28日 14:00:40 +00:00Commented Oct 28, 2018 at 14:00
1 Answer 1
While this code works as intended, there is room for improvement.
Use small functions that do one thing
The main
method does too many things:
- Read input from the console
- Sort the array
- Print the array
These steps are distinct features, their implementations are independent from each other. It would be better if they were in separate functions. That will make the responsibilities of each function clear, and easy to test and verify the correct behavior.
Declare and initialize variables right before you need them
Instead of this:
int size, temp = 0; System.out.println("Enter the size of the array"); Scanner sc = new Scanner(System.in); size = sc.nextInt();
You could declare and initialize size
where needed:
System.out.println("Enter the size of the array");
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
Notice that I completely dropped temp
.
It's not needed here.
You can declare it later when needed.
Unnecessary throws
The main
method declares to throw IOException
but it's unnecessary.
Style
Although this is a valid way to declare an array in Java, it's unusual:
int arr[] = new int[size];
This is the recommended writing style:
int[] arr = new int[size];
The reasoning is that []
is part of the type.
In int arr[]
the type and the variable name are mixed,
in int[] arr
the type is cleanly at the left,
and the variable name is cleanly at the right.
The same goes for String args[]
in the arguments of main
.
-
\$\begingroup\$ Really helpful feedback for a beginner.Very important points raised. \$\endgroup\$indra sen– indra sen2018年10月30日 08:04:50 +00:00Commented Oct 30, 2018 at 8:04