Easy Sorting in Java

Are you confused of using techniques such as Bubble sort or Selection sort in order to sort the elements in an array?
I don't say that these sort techniques are so complex, rather I would say that there are some alternatives for sorting the array using the inbuilt methods in java.

There is a class called Arrays in the util package of java:

java.util.Arrays;

In this class there is an method called Arrays.sort(); This is used to sort the elements of an array in an ascending order. Don't forget to note that the class name Arrays is in plural form.

Pass the name of the array in the parameter of the method and you will find that the elements in the array will be sorted and stored in the same array.

You can also pass the from_Index and to_Index along with the array name in the parameter. The parameter can be of any array type such as int[], char[], byte[], etc.

Take a look at this program: -

/**Importing the required class*/
import java.util.Arrays;
/**Class starts here*/
public class Ascending {
/**Program Execution starts here*/
public static void main(String... Ices) {
/**Declaring an array with some numbers*/
int a[] = {2,3,1,4,7,6,8,9};
/**Method to sort the array*/
Arrays.sort(a);
System.out.println("Ascending Order");
/**Printing the elements using enhanced for loop*/
for(int i:a
System.out.println(i);
}


}

You can also look at the output of the program: -



You can see the array displayed in an ascending order. I think you will be aware of the enhanced for loop used to display the elements in an array one by one. In case of any queries, comment below... Enjoy Coding;)

Comments

Popular posts from this blog

java PROJECT for icse students : CINEMASTER

Magic Square in JAVA