Sort an Array and Insert an Element Inside Array in Java
Sorting an array can be done by using inbuilt sort function while for the insertion we have to create a new array to do so as arrays in Java are immutable. To learn more about sorting in Java follow the article mentioned below:
Sorting: Arrays.sort() in Java with examples
Approach 1:
- Create a new array of size N+1.
- Copy first array in New array.
- Insert number at the end of the array.
- Sort the array.
Example: Inserting an element and then sorting the array.
Java
import java.util.*;
public class Gfg {
public static void main(String args[]) throws Exception
{
int given_number = 1 ;
int array[] = { 6 , 7 , 8 , 2 , 3 , 4 , 5 , 9 , 10 };
int new_array[] = new int [array.length + 1 ];
for ( int i = 0 ; i < array.length; i++) {
new_array[i] = array[i];
}
new_array[new_array.length - 1 ] = given_number;
Arrays.sort(new_array);
for ( int i = 0 ; i < new_array.length; i++)
System.out.print(new_array[i] + " " );
}
}
|
Output
1 2 3 4 5 6 7 8 9 10
Time complexity: O(n log n)
Approach 2:
- Sort the array.
- Create a new array of size N+1.
- Start traversing the given array and copy elements.
- If the given number is less than equal to the number present in the array, append given a number to the new array.
- Copy remaining elements of the given array to the new array.
Example: Inserting an element and then sorting the array.
Java
import java.util.*;
public class Gfg {
public static void main(String args[]) throws Exception
{
int given_number = 1 ;
int array[] = { 6 , 7 , 8 , 2 , 3 , 4 , 5 , 9 , 10 };
Arrays.sort(array);
int new_array[] = new int [array.length + 1 ];
int i = 0 , j = 0 ;
for (i = 0 ; i < new_array.length; i++) {
if (given_number <= array[i]) {
new_array[i] = given_number;
break ;
}
else
new_array[i] = array[j++];
}
for ( int k = i + 1 ; k < new_array.length; k++)
new_array[k] = array[j++];
for (i = 0 ; i < new_array.length; i++)
System.out.print(new_array[i] + " " );
}
}
|
Output
1 2 3 4 5 6 7 8 9 10
Time complexity: O(n log n)
Approach 3:
- Create a set.
- Start adding all the elements in the set.
- Copy remaining elements of the given set to the new array.
Example: Inserting an element and then sorting the array.
Java
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class GFG {
public static void main(String[] args)
{
Integer arr[] = { 6 , 7 , 8 , 2 , 3 , 4 , 5 , 9 , 10 };
Set<Integer> sets
= new HashSet<Integer>(Arrays.asList(arr));
sets.add( 1 );
arr = sets.toArray(arr);
System.out.println(Arrays.toString(arr));
}
}
|
Output
1 2 3 4 5 6 7 8 9 10
Time complexity: O(n log n)
Last Updated :
04 Feb, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...