Trier un tableau en Java

J’essaie de faire un programme qui consiste en un tableau de 10 entiers qui ont tous une valeur aléatoire, jusqu’ici tout va bien.

Cependant, je dois maintenant les sortinger dans l’ordre, de la plus basse à la plus haute valeur, puis l’imprimer sur l’écran. Comment procéder?

(Désolé d’avoir tant de code pour un programme aussi petit, je ne suis pas si bon avec les boucles, juste commencé à travailler avec Java)

public static void main(Ssortingng args[]) { int [] array = new int[10]; array[0] = ((int)(Math.random()*100+1)); array[1] = ((int)(Math.random()*100+1)); array[2] = ((int)(Math.random()*100+1)); array[3] = ((int)(Math.random()*100+1)); array[4] = ((int)(Math.random()*100+1)); array[5] = ((int)(Math.random()*100+1)); array[6] = ((int)(Math.random()*100+1)); array[7] = ((int)(Math.random()*100+1)); array[8] = ((int)(Math.random()*100+1)); array[9] = ((int)(Math.random()*100+1)); System.out.println(array[0] +" " + array[1] +" " + array[2] +" " + array[3] +" " + array[4] +" " + array[5]+" " + array[6]+" " + array[7]+" " + array[8]+" " + array[9] ); } 

Les boucles sont également très utiles pour apprendre, en particulier lorsque vous utilisez des tableaux,

 int[] array = new int[10]; Random rand = new Random(); for (int i = 0; i < array.length; i++) array[i] = rand.nextInt(100) + 1; Arrays.sort(array); System.out.println(Arrays.toString(array)); // in reverse order for (int i = array.length - 1; i >= 0; i--) System.out.print(array[i] + " "); System.out.println(); 

Ajoutez la ligne avant println et votre tableau est sortingé

 Arrays.sort( array ); 

Cela peut vous aider à comprendre les boucles en vous implémentant. Voir Bubble sort est facile à comprendre:

 public void bubbleSort(int[] array) { boolean swapped = true; int j = 0; int tmp; while (swapped) { swapped = false; j++; for (int i = 0; i < array.length - j; i++) { if (array[i] > array[i + 1]) { tmp = array[i]; array[i] = array[i + 1]; array[i + 1] = tmp; swapped = true; } } } } 

Bien sûr, vous ne devriez pas l’utiliser en production car il existe des algorithmes plus performants pour les grandes listes telles que QuickSort ou MergeSort qui sont implémentées par Arrays.sort(array)

Jetez un oeil à Arrays.sort ()

J’étais paresseux et j’ai ajouté les boucles

 import java.util.Arrays; public class Sort { public static void main(Ssortingng args[]) { int [] array = new int[10]; for ( int i = 0 ; i < array.length ; i++ ) { array[i] = ((int)(Math.random()*100+1)); } Arrays.sort( array ); for ( int i = 0 ; i < array.length ; i++ ) { System.out.println(array[i]); } } } 

Votre tableau a une longueur de 10. Vous avez besoin d'une variable ( i ) qui prend les valeurs de 0 à 9 .

 for ( int i = 0 ; i < array.length ; i++ ) ^ ^ ^ | | ------ increment ( i = i + 1 ) | | | +-------------------------- repeat as long i < 10 +------------------------------------------ start value of i Arrays.sort( array ); 

Est une méthode de bibliothèque qui sortinge les tableaux.

 Arrays.sort(yourArray) 

fera le travail parfaitement

Voir ci-dessous, il vous donnera les deux sortingés croissant et décroissant

 import java.util.Arrays; import java.util.Collections; public class SortTestArray { /** * Example method for sorting an Integer array * in reverse & normal order. */ public void sortIntArrayReverseOrder() { Integer[] arrayToSort = new Integer[] { new Integer(48), new Integer(5), new Integer(89), new Integer(80), new Integer(81), new Integer(23), new Integer(45), new Integer(16), new Integer(2) }; System.out.print("General Order is : "); for (Integer i : arrayToSort) { System.out.print(i.intValue() + " "); } Arrays.sort(arrayToSort); System.out.print("\n\nAscending Order is : "); for (Integer i : arrayToSort) { System.out.print(i.intValue() + " "); } Arrays.sort(arrayToSort, Collections.reverseOrder()); System.out.print("\n\nDescinding Order is : "); for (Integer i : arrayToSort) { System.out.print(i.intValue() + " "); } } /** * @param args the command line arguments */ public static void main(Ssortingng[] args) { SortTestArray SortTestArray = new SortTestArray(); SortTestArray.sortIntArrayReverseOrder(); }} 

La sortie sera

 General Order is : 48 5 89 80 81 23 45 16 2 Ascending Order is : 2 5 16 23 45 48 80 81 89 Descinding Order is : 89 81 80 48 45 23 16 5 2 

Remarque: vous pouvez utiliser Math.ranodm au lieu d’append des numéros manuels. Faites-moi savoir si je dois changer le code …

Bonne chance … À la vôtre !!!

Voici comment l’utiliser dans votre programme:

 public static void main(Ssortingng args[]) { int [] array = new int[10]; array[0] = ((int)(Math.random()*100+1)); array[1] = ((int)(Math.random()*100+1)); array[2] = ((int)(Math.random()*100+1)); array[3] = ((int)(Math.random()*100+1)); array[4] = ((int)(Math.random()*100+1)); array[5] = ((int)(Math.random()*100+1)); array[6] = ((int)(Math.random()*100+1)); array[7] = ((int)(Math.random()*100+1)); array[8] = ((int)(Math.random()*100+1)); array[9] = ((int)(Math.random()*100+1)); Arrays.sort(array); System.out.println(array[0] +" " + array[1] +" " + array[2] +" " + array[3] +" " + array[4] +" " + array[5]+" " + array[6]+" " + array[7]+" " + array[8]+" " + array[9] ); } 

juste pour info, vous pouvez maintenant utiliser Java 8 nouvelle API pour sortinger tout type de tableau en utilisant parallelSort

parallelSort utilise le framework Fork / Join introduit dans Java 7 pour affecter les tâches de sorting à plusieurs threads disponibles dans le pool de threads.

les deux méthodes qui peuvent être utilisées pour sortinger le tableau int ,

 parallelSort(int[] a) parallelSort(int[] a,int fromIndex,int toIndex) 
 int[] array = {2, 3, 4, 5, 3, 4, 2, 34, 2, 56, 98, 32, 54}; for (int i = 0; i < array.length; i++) { for (int j = 0; j < array.length; j++) { if (array[i] < array[j]) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } } } 

Vous pouvez sortinger un tableau int avec Arrays.sort( array ) .

Pour un ordre naturel: Array.sort(array)

Pour l’ordre inverse: Array.sort(array, Collections.reverseOrder()); -> C’est une méthode statique dans la classe Collections qui appellera davantage une classe interne de elle-même pour renvoyer un comparateur inverse.

LA VOIE LA PLUS EFFICACE!

 public static void main(Ssortingng args[]) { int [] array = new int[10];//creates an array named array to hold 10 int's for(int x: array)//for-each loop! x = ((int)(Math.random()*100+1)); Array.sort(array); for(int x: array) System.out.println(x+" "); } 

Java 8 offre la possibilité d’utiliser des stream pouvant être utilisés pour sortinger le int[] array tant que:

 int[] sorted = Arrays.stream(array).sorted().toArray(); // option 1 Arrays.parallelSort(array); //option 2 

Comme mentionné dans doc pour parallelSort :

L’algorithme de sorting est une méthode de sorting parallèle qui divise le tableau en sous-tableaux eux-mêmes sortingés puis fusionnés. Lorsque la longueur du sous-tableau atteint une granularité minimale, le sous-tableau est sortingé à l’aide de la méthode Arrays.sort appropriée. Si la longueur du tableau spécifié est inférieure à la granularité minimale, elle est sortingée à l’aide de la méthode Arrays.sort appropriée. L’algorithme nécessite un espace de travail non supérieur à la taille du tableau d’origine. Le pool commun ForkJoin est utilisé pour exécuter des tâches parallèles.

Donc, si le tableau en entrée est inférieur à la granularité (8192 éléments en Java 9 et 4096 en Java 8 je crois), alors parallelSort appelle simplement un algorithme de sorting séquentiel.

Juste au cas où nous voudrions inverser le tableau entier, nous pouvons utiliser le comparateur comme:

 int[] reverseSorted = IntStream.of(array).boxed() .sorted(Comparator.reverseOrder()).mapToInt(i -> i).toArray(); 

Comme Java n’a aucun moyen de sortinger les primitives avec un comparateur personnalisé, nous devons utiliser une boxe intermédiaire ou une autre bibliothèque tierce implémentant un tel sorting primitif.

Vous pouvez utiliser la fonction Arrays.sort () .

 sort() method is a java.util.Arrays class method. Declaration : Arrays.sort(arrName)