Programme Java pour insérer un élément à la position spécifiée dans un tableau
Dans ce tutoriel, nous allons apprendre à ajouter un élément à une position donnée dans un tableau. Pour ce faire, le moyen le plus simple consiste à déplacer les éléments, puis à insérer l'élément à une position spécifique. Mais avant d'aller plus loin, si vous n'êtes pas familier avec les concepts du tableau, alors consultez l'article Tableaux en Java.
Saisie :
Tableau d'origine :5 7 2 3 1 5 6 8
Élément :55
Poste :2
Sortie : 5 7 55 2 3 1 5 6 8
Programme 1 :Ajouter un élément à une position donnée dans un tableau
Dans cette approche, nous utiliserons des boucles pour insérer un élément à une position spécifique.
Algorithme
- Commencer
- Déclarer un tableau
- Initialiser la baie.
- Déclarer l'élément à insérer et positionner où insérer.
- Déclarez un nouveau tableau avec une taille +1.
- Utilisez une boucle for pour parcourir chaque élément.
- Insérez d'abord tous les éléments jusqu'à la position.
- Ensuite, insérez l'élément à la position spécifique.
- Insérez le reste des éléments.
- Renvoyer le nouveau tableau.
- Imprimer le tableau mis à jour.
- Arrêtez.
Vous trouverez ci-dessous le code correspondant.
Le programme ci-dessous montre comment ajouter un élément à une position spécifique dans un tableau à l'aide de boucles.
/*Java Program to add an element in an Array at a specific position*/
import java.util.Arrays;
import java.util.Scanner;
public class Main
{
//Method to add an element in the given specific position
public static int[] addElement(int n, int arr[], int ele, int pos)
{
int i;
// create a new array of size n+1
int newarr[] = new int[n + 1];
// insert the elements from the old array into the new array
for (i = 0; i < n + 1; i++)
{
if (i < pos - 1)
newarr[i] = arr[i]; // insert all elements till position
else if (i == pos - 1)
newarr[i] = ele; // then insert element at specific position
else
newarr[i] = arr[i - 1]; // then insert rest of the elements
}
return newarr;
}
//Driver Method
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n; //Array Size Declaration
System.out.println("Enter the number of elements :");
n=sc.nextInt(); //Array Size Initialization
int arr[]=new int[n]; //Array Declaration
System.out.println("Enter the elements of the array :");
for(int i=0;i<n;i++) //Array Initialization
{
arr[i]=sc.nextInt();
}
System.out.println("Enter the elements you want to insert :");
int ele = sc.nextInt();
// Position to insert
System.out.println("Enter the position where you want to insert :");
int pos = sc.nextInt();
arr = addElement(n, arr, ele, pos);
// print the updated array
System.out.println("\nArray with " + ele + " inserted at position " + pos + ":\n" + Arrays.toString(arr));
}
}
Entrez le nombre d'éléments :10
Entrez les éléments du tableau :8 7 6 9 5 3 4 1 2 9
Entrez les éléments que vous souhaitez insérer :22
Entrez la position où vous souhaitez insérer :2
Tableau avec 22 insérés à la position 2 :
[8, 22, 7, 6, 9, 5, 3, 4, 1, 2, 9]
Programme 2 :Ajouter un élément à une position donnée dans un tableau
Dans cette approche, nous allons convertir le tableau en une liste de tableaux afin d'insérer un élément à une position spécifique.
Algorithme
- Commencer
- Déclarer un tableau
- Initialiser la baie.
- Déclarer l'élément à insérer et positionner où insérer.
- Déclarez une méthode distincte qui insérera l'élément.
- Convertir le tableau en liste de tableaux.
- Ajouter l'élément à la position.
- Reconvertir la liste en tableau.
- Maintenant, imprimez le tableau d'origine.
- Afficher le tableau mis à jour.
- Arrêtez.
Vous trouverez ci-dessous le code correspondant.
Le programme ci-dessous montre comment ajouter un élément à une position spécifique dans un tableau à l'aide de listes de tableaux.
/*Java Program to add an element in an Array at a specific position*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.Collections;
public class Main
{
//Method to add an element in the given specific position
private static void addElement(Integer[] arr, int element, int position)
{
// Coverting array to ArrayList
List<Integer> list = new ArrayList<>(Arrays.asList(arr));
// Adding the element at position
list.add(position - 1, element);
// Converting the list back to array
arr = list.toArray(arr);
// Printing the original array
System.out.println("Initial Array:\n" + Arrays.toString(arr));
// Printing the updated array
System.out.println("\nArray with " + element + " inserted at position "+ position + ":\n" + Arrays.toString(arr));
}
//Driver Method
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n; //Array Size Declaration
System.out.println("Enter the number of elements :");
n=sc.nextInt(); //Array Size Initialization
Integer arr[]=new Integer[n]; //Array Declaration
System.out.println("Enter the elements of the array :");
for(int i=0;i<n;i++) //Array Initialization
{
arr[i]=sc.nextInt();
}
System.out.println("Enter the elements you want to insert :");
int ele = sc.nextInt();
// Position to insert
System.out.println("Enter the position where you want to insert :");
int pos = sc.nextInt();
// Calling the function to insert
addElement(arr, ele, pos);
}
}
Entrez le nombre d'éléments :
10
Entrez les éléments du tableau :
4 5 3 6 8 9 1 2 7 6
Entrez les éléments que vous souhaitez insert :
21
Entrez la position où vous souhaitez insérer :
2
Array initial :
[4, 5, 3, 6, 8, 9, 1 , 2, 7, 6]
Tableau avec 21 insérés en position 2 :
[4, 21, 5, 3, 6, 8, 9, 1, 2, 7, 6]