Sort the given array in ascending order such that elements will be arranged from smallest to largest.
Original Array :
-5 -9 8 12 1 3
Array after sorting :
-9 -5 1 3 8 12
Elements are sorted in such a way that the smallest element will appear on the extreme left which in this case is -9. The largest element will appear on extreme right which in this case is 12.
Approach #1: Bubble sort (using For loop).
- Compare adjacent elements with each other.
- Use nested for loop to keep track.
- Swap the elements if the first element is greater than the second element.
Below is the implementation of the above approach.
Elements of original array: -5 -9 8 12 1 3 Elements of array sorted in ascending order: -9 -5 1 3 8 12
Time Complexity: O(n^2), where n is the length of an array.
Approach #2: Arrays.sort()
The sort() method is a java.util.Arrays class method used to sort array elements. It by default sorts of array elements in ascending order.
Elements of original array: -5 -9 8 12 1 3 Elements of array sorted in ascending order : [-9, -5, 1, 3, 8, 12]
Time Complexity: O(n log(n)), where n is the size of an array.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.