Java Program to Sort the Elements of an Array in Ascending Order
Problem statement: Sort the given array in ascending order such that elements will be arranged from smallest to largest. Consider an illustration below:
Let the original array be as follows:
Array generated after sorting the above array is as follows:
- 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 the extreme right which in this case is 12.
- Using bubble sort(naive)
- Using sort() method of arrays class(optimal)
Approach 1: Using Bubble sort
- 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.
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: Using sort() method of Arrays class
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.
Parameters: Array to be sorted
Return Type: NA
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.
My Personal Notes arrow_drop_up
Please Login to comment...