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.
Approaches:
- Using bubble sort(naive)
- Using sort() method of arrays class(optimal)
Approach 1: Using Bubble sort
Algorithm:
- 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.
Example
Java
class GFG {
static int length;
public static void printArray( int [] array)
{
for ( int i = 0 ; i < length; i++) {
System.out.print(array[i] + " " );
}
System.out.println();
}
public static void sortArray( int [] array)
{
int temporary = 0 ;
for ( int i = 0 ; i < length; i++) {
for ( int j = i + 1 ; j < length; j++) {
if (array[i] > array[j]) {
temporary = array[i];
array[i] = array[j];
array[j] = temporary;
}
}
}
System.out.println(
"Elements of array sorted in ascending order: " );
printArray(array);
}
public static void main(String[] args)
{
int [] array = new int [] { - 5 , - 9 , 8 , 12 , 1 , 3 };
length = array.length;
System.out.print( "Elements of original array: " );
printArray(array);
sortArray(array);
}
}
|
Output
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.
Syntax:
Arrays.sort(arrayName);
Parameters: Array to be sorted
Return Type: NA
Example
Java
import java.util.Arrays;
public class GFG {
public static void main(String[] args)
{
int [] array = new int [] { - 5 , - 9 , 8 , 12 , 1 , 3 };
System.out.print( "Elements of original array: " );
for ( int i = 0 ; i < array.length; i++) {
System.out.print(array[i] + " " );
}
Arrays.sort(array);
System.out.println();
System.out.println(
"Elements of array sorted in ascending order : "
+ Arrays.toString(array));
}
}
|
Output
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.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
06 Jul, 2022
Like Article
Save Article