logo

Comment trier un tableau en Java

Le tri est un moyen d'organiser les éléments d'une liste ou d'un tableau dans un certain ordre. L'ordre peut être croissant ou décroissant. Le numérique et lexicographique L’ordre (alphabétique) est un ordre largement utilisé.

Dans cette section, nous apprendrons comment trier un tableau dans Java dans Ascendant et descendant commande en utilisant le trier() méthode et sans utiliser la méthode sort() . Parallèlement à cela, nous apprendrons également comment trier le sous-tableau dans Java .

Trier le tableau par ordre croissant

Le ordre croissant classe les éléments du plus bas au plus élevé. Il est également connu sous le nom ordre naturel ou ordre numérique . Nous pouvons effectuer le tri des manières suivantes :

dactylographié pour chaque
  • Utilisation de la méthode sort()
  • Sans utiliser la méthode
    • Utiliser la boucle for
    • Utilisation de la méthode définie par l'utilisateur

Utilisation de la méthode sort()

En Java, Tableaux est la classe définie dans lejava.utilpaquet qui fournit trier() méthode pour trier un tableau par ordre croissant. Il utilise Algorithme de tri rapide à double pivot pour le tri. Sa complexité est O(n log(n)) . C'est un statique méthode qui analyse un tableau en paramètre et ne renvoie rien. Nous pouvons l'invoquer directement en utilisant le nom de la classe. Il accepte un tableau de type int, float, double, long, char, byte.

Syntaxe:

 public static void sort(int[] a) 

un est un tableau court.

Remarque : comme la classe Arrays, la classe Collections fournit également la méthode sort() pour trier le tableau. Mais il y a une différence entre eux. La méthode sort() de la classe Arrays fonctionne pour le type primitif tandis que la méthode sort() de la classe Collections fonctionne pour les objets Collections, tels que LinkedList, ArrayList, etc.

Trions un tableau en utilisant la méthode sort() de la classe Arrays.

Dans le programme suivant, nous avons défini un tableau de type entier. Après cela, nous avons invoqué la méthode sort() de la classe Arrays et analysons le tableau à trier. Pour imprimer le tableau trié, nous avons utilisé la boucle for.

SortArrayExample1.java

 import java.util.Arrays; public class SortArrayExample1 { public static void main(String[] args) { //defining an array of integer type int [] array = new int [] {90, 23, 5, 109, 12, 22, 67, 34}; //invoking sort() method of the Arrays class Arrays.sort(array); System.out.println(&apos;Elements of array sorted in ascending order: &apos;); //prints array using the for loop for (int i = 0; i <array.length; i++) { system.out.println(array[i]); } < pre> <p> <strong>Output:</strong> </p> <pre> Array elements in ascending order: 5 12 22 23 34 67 90 109 </pre> <p>In the above program, we can also use the toSting() method of the Arrays class to print the array, as shown in the following statement. It returns a string representation of the specified array.</p> <pre> System.out.printf(Arrays.toString(array)); </pre> <h3>Without Using the Method</h3> <h3>Using the for Loop</h3> <p>In the following example, we have initialized an array of integer type and sort the array in ascending order.</p> <p> <strong>SortArrayExample2.java</strong> </p> <pre> public class SortArrayExample2 { public static void main(String[] args) { //creating an instance of an array int[] arr = new int[] {78, 34, 1, 3, 90, 34, -1, -4, 6, 55, 20, -65}; System.out.println(&apos;Array elements after sorting:&apos;); //sorting logic for (int i = 0; i <arr.length; i++) { for (int j="i" + 1; arr[j]) tmp="arr[i];" arr[i]="arr[j];" arr[j]="tmp;" } prints the sorted element of array system.out.println(arr[i]); < pre> <p> <strong>Output:</strong> </p> <pre> Array elements after sorting: -65 -4 -1 1 3 6 20 34 34 55 78 90 </pre> <h3>Using the User Defined Method</h3> <p>In the following example, we have defined a method named <strong>sortArray()</strong> that contains the logic to sort an array in natural order.</p> <p> <strong>SortArrayExample3.java</strong> </p> <pre> public class SortArrayExample3 { public static void main(String[] args) { int i; //initializing an array int array[] = {12, 45, 1, -1, 0, 4, 56, 23, 89, -21, 56, 27}; System.out.print(&apos;Array elements before sorting: 
&apos;); for(i = 0; i <array.length; i++) system.out.println(array[i]); invoking user defined method sortarray(array, array.length); system.out.print('array elements after sorting: 
'); accessing of the sorted array for(i="0;" i <array.length; { } to sort an in ascending order private static void sortarray(int array[], int n) for (int <n; j="i;" a="array[i];" while ((j> 0) &amp;&amp; (array[j-1] &gt; a)) //returns true when both conditions are true { array[j] = array[j-1]; j--; } array[j] = a; } } } </array.length;></pre> <p> <strong>Output:</strong> </p> <pre> Array elements before sorting: 12 45 1 -1 0 4 56 23 89 -21 56 27 Array elements after sorting: -21 -1 0 1 4 12 23 27 45 56 56 89 </pre> <h2>Sort Array in Descending Order</h2> <p>The <strong>descending order</strong> arranges the elements in the highest to lowest order. We can perform sorting in the following ways:</p> <ul> <li>Using the <strong>reverseOrder()</strong> Method</li> <li>Without using the method <ul> <li>Using the <strong>for</strong> Loop</li> <li>Using the <strong>User Defined</strong> Method</li> </ul></li> </ul> <h3>Using the reverseOrder() Method</h3> <p> <a href="/java-collections-class">Java <strong>Collections</strong> class</a> provides the <strong>reverseOrder()</strong> method to sort the array in reverse-lexicographic order. It is a static method, so we can invoke it directly by using the class name. It does not parse any parameter. It returns a <strong>comparator</strong> that imposes the reverse of the natural ordering (ascending order).</p> <p>It means that the array sorts elements in the ascending order by using the sort() method, after that the reverseOrder() method reverses the natural ordering, and we get the sorted array in descending order.</p> <p> <strong>Syntax:</strong> </p> <pre> public static Comparator reverseOrder() </pre> <p>Suppose, a[] is an array to be sort in the descending order. We will use the reverseOrder() method in the following way:</p> <pre> Arrays.sort(a, Collections.reverseOrder()); </pre> <p>Let&apos;s sorts an array in the descending order.</p> <p>In the following program, a point to be noticed that we have defined an array as <strong>Integer</strong> . Because the reverseOrder() method does not work for the primitive data type.</p> <p> <strong>SortArrayExample4.java</strong> </p> <pre> import java.util.Arrays; import java.util.Collections; public class SortArrayExample4 { public static void main(String[] args) { Integer [] array = {23, -9, 78, 102, 4, 0, -1, 11, 6, 110, 205}; // sorts array[] in descending order Arrays.sort(array, Collections.reverseOrder()); System.out.println(&apos;Array elements in descending order: &apos; +Arrays.toString(array)); } } </pre> <p> <strong>Output:</strong> </p> <pre> Array elements in descending order: [205, 110, 102, 78, 23, 11, 6, 4, 0, -1, -9] </pre> <p>Let&apos;s see another program that sorts array elements in alphabetical order.</p> <p> <strong>SortArrayExample5.java</strong> </p> <pre> import java.util.Arrays; import java.util.Collections; public class SortArrayExample5 { public static void main(String[] args) { String [] strarray = {&apos;Mango&apos;, &apos;Apple&apos;, &apos;Grapes&apos;, &apos;Papaya&apos;, &apos;Pineapple&apos;, &apos;Banana&apos;, &apos;Orange&apos;}; // sorts array[] in descending order Arrays.sort(strarray, Collections.reverseOrder()); System.out.println(&apos;Array elements in descending order: &apos; +Arrays.toString(strarray)); } } </pre> <p> <strong>Output:</strong> </p> <pre> Array elements in descending order: [Papaya, Pineapple, Orange, Mango, Grapes, Banana, Apple] </pre> <h3>Without Using the Method</h3> <h3>Using the for Loop</h3> <p>In the following example, we have initialized an integer array and perform sorting in descending order.</p> <p> <strong>SortArrayExample6.java</strong> </p> <pre> public class SortArrayExample6 { public static void main(String[] args) { int temp; //initializing an array int a[]={12,5,56,-2,32,2,-26,9,43,94,-78}; for (int i = 0; i <a.length; i++) { for (int j="i" + 1; < a.length; j++) if (a[i] a[j]) temp="a[i];" a[i]="a[j];" a[j]="temp;" } system.out.println('array elements in descending order:'); accessing element of the array i="0;" - system.out.println(a[i]); pre> <p> <strong>Output:</strong> </p> <pre> Array elements in descending order: 94 56 43 32 12 9 5 2 -2 -26 -78 </pre> <h3>Using the User Defined Method</h3> <p> <strong>SortArrayExample7.java</strong> </p> <pre> import java.util.Scanner; public class SortArrayExample7 { public static void main(String[] args) { int n, temp; Scanner s = new Scanner(System.in); System.out.print(&apos;Enter the number of elements: &apos;); n = s.nextInt(); int a[] = new int[n]; System.out.println(&apos;Enter the elements of the array: &apos;); for (int i = 0; i <n; i++) { a[i]="s.nextInt();" } for (int i="0;" < n; j="i" + 1; j++) if (a[i] a[j]) temp="a[i];" a[j]="temp;" system.out.println('array elements in descending order:'); n - system.out.println(a[i]); system.out.print(a[n 1]); pre> <p> <strong>Output:</strong> </p> <pre> Enter the number of elements: 7 Enter the elements of the array: 12 5 56 -2 32 2 -26 Array elements in descending order: 56 32 12 5 2 -2 -26 </pre> <h2>How to Sort Subarray</h2> <p>An array derived from the array is known as <strong>subarray</strong> . Suppose, <strong>a[]</strong> is an array having the elements [12, 90, 34, 2, 45, 3, 22, 18, 5, 78] and we want to sort array elements from 34 to 18. It will sort the subarray <strong>[34, 2, 45, 3, 22, 18]</strong> and keep the other elements as it is.</p> <p>To sort the subarray, the Arrays class provides the static method named <strong>sort()</strong> . It sorts the specified range of the array into ascending order. We can also sort the array of type <strong>long, double, float, char, byte,</strong> etc.</p> <p> <strong>Syntax:</strong> </p> <pre> public static void sort(int[] a, int fromIndex, int toIndex) </pre> <p>The method parses the following three parameters:</p> <ul> <tr><td>a:</td> An array to be sort. </tr><tr><td>fromIndex:</td> The index of the first element of the subarray. It participates in the sorting. </tr><tr><td>toIndex:</td> The index of the last element of the subarray. It does not participate in the sorting. </tr></ul> <p>If formIndex is equal to the toIndex, the range to be sorted is empty. It throws IllegalArgumentException if <strong>fomIndex is greater than toIndex</strong> . It also throws ArrayIndexOutOfBoundsException if <strong>fromIndex a.length</strong> .</p> <p>Let&apos;s sort a subarray through a Java program.</p> <p> <strong>SortSubarrayExample.java</strong> </p> <pre> import java.util.Arrays; public class SortSubarrayExample { public static void main(String[] args) { //defining an array int[] a = {12, 90, 34, 2, 45, 3, 22, 18, 5, 78}; // sorts subarray form index 2 to 7 Arrays.sort(a, 2, 7); //prints array using the for loop for (int i = 0; i <a.length; i++) { system.out.println(a[i]); } < pre> <p> <strong>Output:</strong> </p> <pre> Sorted Subarray: 12 90 2 3 22 34 45 18 5 78 </pre> <hr></a.length;></pre></n;></pre></a.length;></pre></arr.length;></pre></array.length;>

Dans le programme ci-dessus, nous pouvons également utiliser la méthode toSting() de la classe Arrays pour imprimer le tableau, comme indiqué dans l'instruction suivante. Il renvoie une représentation sous forme de chaîne du tableau spécifié.

 System.out.printf(Arrays.toString(array)); 

Sans utiliser la méthode

Utiliser la boucle for

Dans l'exemple suivant, nous avons initialisé un tableau de type entier et trié le tableau par ordre croissant.

SortArrayExample2.java

 public class SortArrayExample2 { public static void main(String[] args) { //creating an instance of an array int[] arr = new int[] {78, 34, 1, 3, 90, 34, -1, -4, 6, 55, 20, -65}; System.out.println(&apos;Array elements after sorting:&apos;); //sorting logic for (int i = 0; i <arr.length; i++) { for (int j="i" + 1; arr[j]) tmp="arr[i];" arr[i]="arr[j];" arr[j]="tmp;" } prints the sorted element of array system.out.println(arr[i]); < pre> <p> <strong>Output:</strong> </p> <pre> Array elements after sorting: -65 -4 -1 1 3 6 20 34 34 55 78 90 </pre> <h3>Using the User Defined Method</h3> <p>In the following example, we have defined a method named <strong>sortArray()</strong> that contains the logic to sort an array in natural order.</p> <p> <strong>SortArrayExample3.java</strong> </p> <pre> public class SortArrayExample3 { public static void main(String[] args) { int i; //initializing an array int array[] = {12, 45, 1, -1, 0, 4, 56, 23, 89, -21, 56, 27}; System.out.print(&apos;Array elements before sorting: 
&apos;); for(i = 0; i <array.length; i++) system.out.println(array[i]); invoking user defined method sortarray(array, array.length); system.out.print(\'array elements after sorting: 
\'); accessing of the sorted array for(i="0;" i <array.length; { } to sort an in ascending order private static void sortarray(int array[], int n) for (int <n; j="i;" a="array[i];" while ((j> 0) &amp;&amp; (array[j-1] &gt; a)) //returns true when both conditions are true { array[j] = array[j-1]; j--; } array[j] = a; } } } </array.length;></pre> <p> <strong>Output:</strong> </p> <pre> Array elements before sorting: 12 45 1 -1 0 4 56 23 89 -21 56 27 Array elements after sorting: -21 -1 0 1 4 12 23 27 45 56 56 89 </pre> <h2>Sort Array in Descending Order</h2> <p>The <strong>descending order</strong> arranges the elements in the highest to lowest order. We can perform sorting in the following ways:</p> <ul> <li>Using the <strong>reverseOrder()</strong> Method</li> <li>Without using the method <ul> <li>Using the <strong>for</strong> Loop</li> <li>Using the <strong>User Defined</strong> Method</li> </ul></li> </ul> <h3>Using the reverseOrder() Method</h3> <p> <a href="/java-collections-class">Java <strong>Collections</strong> class</a> provides the <strong>reverseOrder()</strong> method to sort the array in reverse-lexicographic order. It is a static method, so we can invoke it directly by using the class name. It does not parse any parameter. It returns a <strong>comparator</strong> that imposes the reverse of the natural ordering (ascending order).</p> <p>It means that the array sorts elements in the ascending order by using the sort() method, after that the reverseOrder() method reverses the natural ordering, and we get the sorted array in descending order.</p> <p> <strong>Syntax:</strong> </p> <pre> public static Comparator reverseOrder() </pre> <p>Suppose, a[] is an array to be sort in the descending order. We will use the reverseOrder() method in the following way:</p> <pre> Arrays.sort(a, Collections.reverseOrder()); </pre> <p>Let&apos;s sorts an array in the descending order.</p> <p>In the following program, a point to be noticed that we have defined an array as <strong>Integer</strong> . Because the reverseOrder() method does not work for the primitive data type.</p> <p> <strong>SortArrayExample4.java</strong> </p> <pre> import java.util.Arrays; import java.util.Collections; public class SortArrayExample4 { public static void main(String[] args) { Integer [] array = {23, -9, 78, 102, 4, 0, -1, 11, 6, 110, 205}; // sorts array[] in descending order Arrays.sort(array, Collections.reverseOrder()); System.out.println(&apos;Array elements in descending order: &apos; +Arrays.toString(array)); } } </pre> <p> <strong>Output:</strong> </p> <pre> Array elements in descending order: [205, 110, 102, 78, 23, 11, 6, 4, 0, -1, -9] </pre> <p>Let&apos;s see another program that sorts array elements in alphabetical order.</p> <p> <strong>SortArrayExample5.java</strong> </p> <pre> import java.util.Arrays; import java.util.Collections; public class SortArrayExample5 { public static void main(String[] args) { String [] strarray = {&apos;Mango&apos;, &apos;Apple&apos;, &apos;Grapes&apos;, &apos;Papaya&apos;, &apos;Pineapple&apos;, &apos;Banana&apos;, &apos;Orange&apos;}; // sorts array[] in descending order Arrays.sort(strarray, Collections.reverseOrder()); System.out.println(&apos;Array elements in descending order: &apos; +Arrays.toString(strarray)); } } </pre> <p> <strong>Output:</strong> </p> <pre> Array elements in descending order: [Papaya, Pineapple, Orange, Mango, Grapes, Banana, Apple] </pre> <h3>Without Using the Method</h3> <h3>Using the for Loop</h3> <p>In the following example, we have initialized an integer array and perform sorting in descending order.</p> <p> <strong>SortArrayExample6.java</strong> </p> <pre> public class SortArrayExample6 { public static void main(String[] args) { int temp; //initializing an array int a[]={12,5,56,-2,32,2,-26,9,43,94,-78}; for (int i = 0; i <a.length; i++) { for (int j="i" + 1; < a.length; j++) if (a[i] a[j]) temp="a[i];" a[i]="a[j];" a[j]="temp;" } system.out.println(\'array elements in descending order:\'); accessing element of the array i="0;" - system.out.println(a[i]); pre> <p> <strong>Output:</strong> </p> <pre> Array elements in descending order: 94 56 43 32 12 9 5 2 -2 -26 -78 </pre> <h3>Using the User Defined Method</h3> <p> <strong>SortArrayExample7.java</strong> </p> <pre> import java.util.Scanner; public class SortArrayExample7 { public static void main(String[] args) { int n, temp; Scanner s = new Scanner(System.in); System.out.print(&apos;Enter the number of elements: &apos;); n = s.nextInt(); int a[] = new int[n]; System.out.println(&apos;Enter the elements of the array: &apos;); for (int i = 0; i <n; i++) { a[i]="s.nextInt();" } for (int i="0;" < n; j="i" + 1; j++) if (a[i] a[j]) temp="a[i];" a[j]="temp;" system.out.println(\'array elements in descending order:\'); n - system.out.println(a[i]); system.out.print(a[n 1]); pre> <p> <strong>Output:</strong> </p> <pre> Enter the number of elements: 7 Enter the elements of the array: 12 5 56 -2 32 2 -26 Array elements in descending order: 56 32 12 5 2 -2 -26 </pre> <h2>How to Sort Subarray</h2> <p>An array derived from the array is known as <strong>subarray</strong> . Suppose, <strong>a[]</strong> is an array having the elements [12, 90, 34, 2, 45, 3, 22, 18, 5, 78] and we want to sort array elements from 34 to 18. It will sort the subarray <strong>[34, 2, 45, 3, 22, 18]</strong> and keep the other elements as it is.</p> <p>To sort the subarray, the Arrays class provides the static method named <strong>sort()</strong> . It sorts the specified range of the array into ascending order. We can also sort the array of type <strong>long, double, float, char, byte,</strong> etc.</p> <p> <strong>Syntax:</strong> </p> <pre> public static void sort(int[] a, int fromIndex, int toIndex) </pre> <p>The method parses the following three parameters:</p> <ul> <tr><td>a:</td> An array to be sort. </tr><tr><td>fromIndex:</td> The index of the first element of the subarray. It participates in the sorting. </tr><tr><td>toIndex:</td> The index of the last element of the subarray. It does not participate in the sorting. </tr></ul> <p>If formIndex is equal to the toIndex, the range to be sorted is empty. It throws IllegalArgumentException if <strong>fomIndex is greater than toIndex</strong> . It also throws ArrayIndexOutOfBoundsException if <strong>fromIndex a.length</strong> .</p> <p>Let&apos;s sort a subarray through a Java program.</p> <p> <strong>SortSubarrayExample.java</strong> </p> <pre> import java.util.Arrays; public class SortSubarrayExample { public static void main(String[] args) { //defining an array int[] a = {12, 90, 34, 2, 45, 3, 22, 18, 5, 78}; // sorts subarray form index 2 to 7 Arrays.sort(a, 2, 7); //prints array using the for loop for (int i = 0; i <a.length; i++) { system.out.println(a[i]); } < pre> <p> <strong>Output:</strong> </p> <pre> Sorted Subarray: 12 90 2 3 22 34 45 18 5 78 </pre> <hr></a.length;></pre></n;></pre></a.length;></pre></arr.length;>

Utilisation de la méthode définie par l'utilisateur

Dans l'exemple suivant, nous avons défini une méthode nommée sortArray() qui contient la logique permettant de trier un tableau dans l'ordre naturel.

SortArrayExample3.java

 public class SortArrayExample3 { public static void main(String[] args) { int i; //initializing an array int array[] = {12, 45, 1, -1, 0, 4, 56, 23, 89, -21, 56, 27}; System.out.print(&apos;Array elements before sorting: 
&apos;); for(i = 0; i <array.length; i++) system.out.println(array[i]); invoking user defined method sortarray(array, array.length); system.out.print(\'array elements after sorting: 
\'); accessing of the sorted array for(i="0;" i <array.length; { } to sort an in ascending order private static void sortarray(int array[], int n) for (int <n; j="i;" a="array[i];" while ((j> 0) &amp;&amp; (array[j-1] &gt; a)) //returns true when both conditions are true { array[j] = array[j-1]; j--; } array[j] = a; } } } </array.length;>

Sortir:

types de réseau
 Array elements before sorting: 12 45 1 -1 0 4 56 23 89 -21 56 27 Array elements after sorting: -21 -1 0 1 4 12 23 27 45 56 56 89 

Trier le tableau par ordre décroissant

Le Ordre décroissant classe les éléments du plus haut au plus bas. Nous pouvons effectuer le tri des manières suivantes :

  • En utilisant le ordre inverse() Méthode
  • Sans utiliser la méthode
    • En utilisant le pour Boucle
    • En utilisant le Défini par l'utilisateur Méthode

Utilisation de la méthode reverseOrder()

Java Collections classe fournit le ordre inverse() méthode pour trier le tableau dans l’ordre lexicographique inverse. C'est une méthode statique, nous pouvons donc l'invoquer directement en utilisant le nom de la classe. Il n'analyse aucun paramètre. Il renvoie un comparateur qui impose l'inverse de l'ordre naturel (ordre ascendant).

Cela signifie que le tableau trie les éléments dans l'ordre croissant en utilisant la méthode sort(), après quoi la méthode reverseOrder() inverse l'ordre naturel et nous obtenons le tableau trié par ordre décroissant.

Syntaxe:

 public static Comparator reverseOrder() 

Supposons que a[] soit un tableau à trier par ordre décroissant. Nous utiliserons la méthode reverseOrder() de la manière suivante :

 Arrays.sort(a, Collections.reverseOrder()); 

Trions un tableau par ordre décroissant.

Dans le programme suivant, il convient de noter que nous avons défini un tableau comme Entier . Parce que la méthode reverseOrder() ne fonctionne pas pour le type de données primitif.

SortArrayExample4.java

 import java.util.Arrays; import java.util.Collections; public class SortArrayExample4 { public static void main(String[] args) { Integer [] array = {23, -9, 78, 102, 4, 0, -1, 11, 6, 110, 205}; // sorts array[] in descending order Arrays.sort(array, Collections.reverseOrder()); System.out.println(&apos;Array elements in descending order: &apos; +Arrays.toString(array)); } } 

Sortir:

 Array elements in descending order: [205, 110, 102, 78, 23, 11, 6, 4, 0, -1, -9] 

Voyons un autre programme qui trie les éléments d'un tableau par ordre alphabétique.

SortArrayExample5.java

java pendant la condition
 import java.util.Arrays; import java.util.Collections; public class SortArrayExample5 { public static void main(String[] args) { String [] strarray = {&apos;Mango&apos;, &apos;Apple&apos;, &apos;Grapes&apos;, &apos;Papaya&apos;, &apos;Pineapple&apos;, &apos;Banana&apos;, &apos;Orange&apos;}; // sorts array[] in descending order Arrays.sort(strarray, Collections.reverseOrder()); System.out.println(&apos;Array elements in descending order: &apos; +Arrays.toString(strarray)); } } 

Sortir:

 Array elements in descending order: [Papaya, Pineapple, Orange, Mango, Grapes, Banana, Apple] 

Sans utiliser la méthode

Utiliser la boucle for

Dans l'exemple suivant, nous avons initialisé un tableau d'entiers et effectué un tri par ordre décroissant.

SortArrayExample6.java

 public class SortArrayExample6 { public static void main(String[] args) { int temp; //initializing an array int a[]={12,5,56,-2,32,2,-26,9,43,94,-78}; for (int i = 0; i <a.length; i++) { for (int j="i" + 1; < a.length; j++) if (a[i] a[j]) temp="a[i];" a[i]="a[j];" a[j]="temp;" } system.out.println(\'array elements in descending order:\'); accessing element of the array i="0;" - system.out.println(a[i]); pre> <p> <strong>Output:</strong> </p> <pre> Array elements in descending order: 94 56 43 32 12 9 5 2 -2 -26 -78 </pre> <h3>Using the User Defined Method</h3> <p> <strong>SortArrayExample7.java</strong> </p> <pre> import java.util.Scanner; public class SortArrayExample7 { public static void main(String[] args) { int n, temp; Scanner s = new Scanner(System.in); System.out.print(&apos;Enter the number of elements: &apos;); n = s.nextInt(); int a[] = new int[n]; System.out.println(&apos;Enter the elements of the array: &apos;); for (int i = 0; i <n; i++) { a[i]="s.nextInt();" } for (int i="0;" < n; j="i" + 1; j++) if (a[i] a[j]) temp="a[i];" a[j]="temp;" system.out.println(\'array elements in descending order:\'); n - system.out.println(a[i]); system.out.print(a[n 1]); pre> <p> <strong>Output:</strong> </p> <pre> Enter the number of elements: 7 Enter the elements of the array: 12 5 56 -2 32 2 -26 Array elements in descending order: 56 32 12 5 2 -2 -26 </pre> <h2>How to Sort Subarray</h2> <p>An array derived from the array is known as <strong>subarray</strong> . Suppose, <strong>a[]</strong> is an array having the elements [12, 90, 34, 2, 45, 3, 22, 18, 5, 78] and we want to sort array elements from 34 to 18. It will sort the subarray <strong>[34, 2, 45, 3, 22, 18]</strong> and keep the other elements as it is.</p> <p>To sort the subarray, the Arrays class provides the static method named <strong>sort()</strong> . It sorts the specified range of the array into ascending order. We can also sort the array of type <strong>long, double, float, char, byte,</strong> etc.</p> <p> <strong>Syntax:</strong> </p> <pre> public static void sort(int[] a, int fromIndex, int toIndex) </pre> <p>The method parses the following three parameters:</p> <ul> <tr><td>a:</td> An array to be sort. </tr><tr><td>fromIndex:</td> The index of the first element of the subarray. It participates in the sorting. </tr><tr><td>toIndex:</td> The index of the last element of the subarray. It does not participate in the sorting. </tr></ul> <p>If formIndex is equal to the toIndex, the range to be sorted is empty. It throws IllegalArgumentException if <strong>fomIndex is greater than toIndex</strong> . It also throws ArrayIndexOutOfBoundsException if <strong>fromIndex a.length</strong> .</p> <p>Let&apos;s sort a subarray through a Java program.</p> <p> <strong>SortSubarrayExample.java</strong> </p> <pre> import java.util.Arrays; public class SortSubarrayExample { public static void main(String[] args) { //defining an array int[] a = {12, 90, 34, 2, 45, 3, 22, 18, 5, 78}; // sorts subarray form index 2 to 7 Arrays.sort(a, 2, 7); //prints array using the for loop for (int i = 0; i <a.length; i++) { system.out.println(a[i]); } < pre> <p> <strong>Output:</strong> </p> <pre> Sorted Subarray: 12 90 2 3 22 34 45 18 5 78 </pre> <hr></a.length;></pre></n;></pre></a.length;>

Utilisation de la méthode définie par l'utilisateur

SortArrayExample7.java

 import java.util.Scanner; public class SortArrayExample7 { public static void main(String[] args) { int n, temp; Scanner s = new Scanner(System.in); System.out.print(&apos;Enter the number of elements: &apos;); n = s.nextInt(); int a[] = new int[n]; System.out.println(&apos;Enter the elements of the array: &apos;); for (int i = 0; i <n; i++) { a[i]="s.nextInt();" } for (int i="0;" < n; j="i" + 1; j++) if (a[i] a[j]) temp="a[i];" a[j]="temp;" system.out.println(\'array elements in descending order:\'); n - system.out.println(a[i]); system.out.print(a[n 1]); pre> <p> <strong>Output:</strong> </p> <pre> Enter the number of elements: 7 Enter the elements of the array: 12 5 56 -2 32 2 -26 Array elements in descending order: 56 32 12 5 2 -2 -26 </pre> <h2>How to Sort Subarray</h2> <p>An array derived from the array is known as <strong>subarray</strong> . Suppose, <strong>a[]</strong> is an array having the elements [12, 90, 34, 2, 45, 3, 22, 18, 5, 78] and we want to sort array elements from 34 to 18. It will sort the subarray <strong>[34, 2, 45, 3, 22, 18]</strong> and keep the other elements as it is.</p> <p>To sort the subarray, the Arrays class provides the static method named <strong>sort()</strong> . It sorts the specified range of the array into ascending order. We can also sort the array of type <strong>long, double, float, char, byte,</strong> etc.</p> <p> <strong>Syntax:</strong> </p> <pre> public static void sort(int[] a, int fromIndex, int toIndex) </pre> <p>The method parses the following three parameters:</p> <ul> <tr><td>a:</td> An array to be sort. </tr><tr><td>fromIndex:</td> The index of the first element of the subarray. It participates in the sorting. </tr><tr><td>toIndex:</td> The index of the last element of the subarray. It does not participate in the sorting. </tr></ul> <p>If formIndex is equal to the toIndex, the range to be sorted is empty. It throws IllegalArgumentException if <strong>fomIndex is greater than toIndex</strong> . It also throws ArrayIndexOutOfBoundsException if <strong>fromIndex a.length</strong> .</p> <p>Let&apos;s sort a subarray through a Java program.</p> <p> <strong>SortSubarrayExample.java</strong> </p> <pre> import java.util.Arrays; public class SortSubarrayExample { public static void main(String[] args) { //defining an array int[] a = {12, 90, 34, 2, 45, 3, 22, 18, 5, 78}; // sorts subarray form index 2 to 7 Arrays.sort(a, 2, 7); //prints array using the for loop for (int i = 0; i <a.length; i++) { system.out.println(a[i]); } < pre> <p> <strong>Output:</strong> </p> <pre> Sorted Subarray: 12 90 2 3 22 34 45 18 5 78 </pre> <hr></a.length;></pre></n;>

Comment trier le sous-tableau

Un tableau dérivé du tableau est appelé sous-tableau . Supposer, un[] est un tableau ayant les éléments [12, 90, 34, 2, 45, 3, 22, 18, 5, 78] et nous voulons trier les éléments du tableau de 34 à 18. Il triera le sous-tableau [34, 2, 45, 3, 22, 18] et gardez les autres éléments tels quels.

Pour trier le sous-tableau, la classe Arrays fournit la méthode statique nommée trier() . Il trie la plage spécifiée du tableau par ordre croissant. Nous pouvons également trier le tableau de type long, double, float, char, octet, etc.

Syntaxe:

 public static void sort(int[] a, int fromIndex, int toIndex) 

La méthode analyse les trois paramètres suivants :

comment récupérer des applications cachées
    un:Un tableau à trier.de l'index :L'index du premier élément du sous-tableau. Il participe au tri.indexer:L'index du dernier élément du sous-tableau. Il ne participe pas au tri.

Si formIndex est égal à toIndex, la plage à trier est vide. Il lance IllegalArgumentException si fomIndex est supérieur à toIndex . Il lance également ArrayIndexOutOfBoundsException si fromIndex a.length .

Trions un sous-tableau via un programme Java.

SortSubarrayExample.java

 import java.util.Arrays; public class SortSubarrayExample { public static void main(String[] args) { //defining an array int[] a = {12, 90, 34, 2, 45, 3, 22, 18, 5, 78}; // sorts subarray form index 2 to 7 Arrays.sort(a, 2, 7); //prints array using the for loop for (int i = 0; i <a.length; i++) { system.out.println(a[i]); } < pre> <p> <strong>Output:</strong> </p> <pre> Sorted Subarray: 12 90 2 3 22 34 45 18 5 78 </pre> <hr></a.length;>