2012-01-20 14 views
127

Sto provando a creare un programma che consiste in un array di 10 numeri interi che ha tutti un valore casuale, finora così buono.Ordina una matrice in Java

Tuttavia, ora ho bisogno di ordinarli in ordine dal più basso al più alto valore e quindi stamparlo sullo schermo, come potrei fare per farlo?

(Ci scusiamo per avere così tanto codice di un programma che piccolo, io non è che il bene con i loop, appena iniziato a lavorare con Java)

public static void main(String 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]);   

} 

risposta

161

loop sono anche molto utili per conoscere, esp Quando si utilizzano matrici,

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(); 
+3

cosa succede se voglio stampare in ordine inverso usando lo stesso codice sopra .... –

+5

@FahimParkar 'Arrays.Reverse (array);' – UnKnown

5

Puoi ordina un array int con Arrays.sort(array).

+0

Potrei avere un esempio su come usarlo nel mio programma? – Lukas

+0

Guarda il codice in [post] (http://stackoverflow.com/a/8938322/1158170) – rauschen

155

aggiungere la riga prima del println e l'array ordinato ottiene

Arrays.sort(array); 
+8

Potrei avere un esempio su come usarlo nel mio programma? – Lukas

33

Può aiutare a capire i cicli di attuazione da soli. Vedere bubble sort è facile da capire:

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; 
      } 
     } 
    } 
} 

Naturalmente, non si dovrebbe usare in produzione in quanto vi sono migliori algoritmi performanti per i grandi elenchi come QuickSort o MergeSort che sono attuate da

16

ero pigro e ha aggiunto i loop

import java.util.Arrays; 


public class Sort { 
    public static void main(String 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]); 
     } 
    } 
} 

tuo array ha una lunghezza di 10. È necessario una variabile (i) che prende i valori da 0 a 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); 

È un metodo di libreria che ordina gli array.

+0

Che bel modo di mostrare per la descrizione del loop –

6

Ecco come utilizzare questo nel vostro programma:

public static void main(String 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]);   

} 
6

Vedi sotto, che vi darà ordinato crescente e decrescente entrambi

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(String[] args) { 
    SortTestArray SortTestArray = new SortTestArray(); 
    SortTestArray.sortIntArrayReverseOrder(); 
}} 

Uscita sarà

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 

Nota: È possibile utilizzare Math.ranodm invece di aggiungere numeri manuali. Fammi sapere se ho bisogno di cambiare il codice ...

Buona fortuna ... Saluti !!!

+0

Non si dovrebbe usare 'Intero' quando puoi usare 'int', in tal caso causerà lentezza. – JonasCz

14
Arrays.sort(yourArray) 

farà il lavoro perfettamente

3

Ecco quello che ho fatto:

System.out.print("Enter number of student: "); 
input = myScan.nextInt(); 

int[] scores = new int[input]; 
String[] students = new String[input]; 
try { 

    for (int index = 0; index < input; index++) { 
     System.out.print("Enter student: "); 
     students[index] = myBuff.readLine(); 
     System.out.print("Enter score for " + students[index] + ": "); 
     scores[index] = myScan.nextInt(); 
    } 

    //Sorting the numbers 
    for (int index = 0; index < input; index++) { 
     for (int index1 = 0; index1 < input - 1; index1++) { 
      if (scores[index1] > scores[index1 + 1]) { 

       contain = scores[index1]; 
       containS = students[index1]; 
       scores[index1] = scores[index1 + 1]; 
       students[index1] = students[index1 + 1]; 
       scores[index1 + 1] = contain; 
       students[index1 + 1] = containS; 

      } 
     } 
    } 
1
import java.util.*; 

public class Sample4You { 

    public static void main(String[] args) { 

     int[] YourList = new int[10]; 
     int x; 

     //this is for placing the randomly generated numbers into each index 
     for (x = 1; x < 10; x++) { 
      YourList[x] = (int) (Math.random() * 100); 
     } 

     Arrays.sort(YourList);//we must sort the array "YourList"from least 2 greatest 

     //now we print all the numbers 1 by 1 -- 
     for (x = 0; x < YourList.length; x++) { 
      System.out.println("Number in index [" + x + "] = " + YourList[x]); 
     } 
    } 
} 
-2

Va come questo nel codice.

public static void main(String 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)); 

    Array.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]); 

} 
+1

Si prega di non inviare solo la risposta del codice. Prova a dare una spiegazione del tuo codice e come li aiuta. – JonasCz

+0

non dovrebbe Arrays.sort (array) invece di Array.sort (array)? –

5

appena cronaca, è ora possibile utilizzare Java 8 nuove API per l'ordinamento di qualsiasi tipo di matrice utilizzando parallelSort

parallelSort utilizza Fork/quadro introdotto in Java 7 Iscrivetevi per assegnare i compiti di smistamento a più thread disponibili nel pool di thread.

i due metodi che possono essere utilizzati per ordinare int matrice,

parallelSort(int[] a) 
parallelSort(int[] a,int fromIndex,int toIndex) 
2

modo più efficace!

public static void main(String 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+" "); 
} 
1
int []array = {5,8,2,1,3,0,1,7}; 
    int min = 0; 
    int temp; 

    for(int i=0; i<array.length; i++) 
    { 
     min = i; 
     for(int j=i; j< array.length; j++) 
     { 
      if(array[j] < array[min]) 
       min = j; 

     } 
     temp = array[i]; 
     array[i] = array[min]; 
     array[min] = temp; 
    } 
+3

Si prega di non inviare solo la risposta del codice. Prova a dare una spiegazione del tuo codice e come li aiuta. La soluzione invertita –

5
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; 
     } 
    } 
} 
3

Per ordine naturale: Array.sort(array)

Per la retromarcia ordine: Array.sort(array, Collections.reverseOrder()); -> Si tratta di un metodo statico in classe Collections che sarà ulteriormente chiamare una classe interna di sé per restituire un comparatore inverso.

+0

non funziona per i primitivi, sfortunatamente. IntStream.range (0, size) .map (i -> array [size-i-1]). ToArray(); lo fa. size = array.length; –

0

È possibile utilizzare la funzione Arrays.sort().

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

soluzione elegante è quella di utilizzare flusso API.It non è il modo migliore per utilizzare qui, perché si spendono le risorse per convertire da int -> Integer, ma ho voluto mostrare che API Stream è forte strumento per crea qualsiasi logica tu voglia in diverse situazioni.

int[] ints= {53,95,1,3,534,94,4356,5,1,114}; 
    List<Integer> integers = new ArrayList<>(); 
    Collections.addAll(integers, Arrays.stream(ints).boxed().toArray(Integer[]::new));//Converting int into Integer and put to arrayList 
    integers.sort(Comparator.comparingInt(o -> o));//sorting 
    integers.forEach(System.out::println);//printing 

In termini di prestazioni è meglio utilizzare matrici di classe.

Arrays.sort(ints); 
-1

Sto usando un ciclo per impostare la matrice valori

int[] array = new int[10]; 

for (int i = 0; i < array.length; i++) { 
      int x = (int) (Math.random() * 100+1); 
      array[i] = x; 
     } 

     boolean flag = true; //flag to exit while loop 
     int tempValue; // temporary value for swapping the array values 
     while (flag) { 
      flag = false; 
      for (int i = 0; i < (array.length) - (1); i++) { 
       if (array[i] > array[i + 1]) { 
        tempValue = array[i]; 
        array[i] = array[i + 1]; 
        array[i + 1] = tempValue; 
        flag = true; 
       } 
      } 
     } 
     System.out.println("Ascending order\n" +Arrays.toString(array)); // print the ordered array values 
+0

perché hai postato questo? –

+0

Come migliora la filettatura? – Wndrr

+0

per mostrare come funziona l'ordinamento. semplicemente così –

0

Ti potrebbe piacere questo ::

public static void main(String 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]); 

    Arrays.sort(array); 
    System.out.println("After sorting array:: "); 
    for (int i = 0; i < array.length; i++) { 
     System.out.print(array[i] + " "); 
    } 
} 

Bisogna importare java.util.Arrays; in programma di utilizzare il metodo Arrays.sort .

1

Java 8 fornisce la possibilità di utilizzare flussi che possono essere utilizzati per ordinare int[] array come:

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

Come menzionato nella doc per parralelSort:

L'algoritmo di ordinamento è una sorta parallelo -merge che interrompe l'array in matrici secondarie che sono a loro volta ordinate e quindi unite. Quando la lunghezza della sottostruttura raggiunge una granularità minima, la matrice secondaria è ordinata utilizzando il metodo Arrays.sort appropriato. Se la lunghezza della matrice specificata è inferiore alla granularità minima, allora è ordinata utilizzando il metodo Arrays.sort appropriato. L'algoritmo richiede uno spazio di lavoro non superiore alla dimensione dell'array originale . Il pool comune ForkJoin viene utilizzato per eseguire attività parallele.

Quindi, se la matrice di ingresso è inferiore a granularità (8192 elementi in Java 9 e 4096 in Java 8 credo), quindi parallelSort chiama semplicemente algoritmo di ordinamento sequenziale.

Solo nel caso vogliamo invertire ordinare l'array intero possiamo fare uso del comparatore come:

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

Dato che Java non ha alcun modo per ordinare primitive con comparatore personalizzato, dobbiamo usare la boxe intermedio o qualche altra libreria di terze parti che implementa tale selezione primitiva.

0

soluzione semplice:

private static void sortArray(int[] arr) { 

    for (int i = 0; i <arr.length-1; i++) { 
     for (int j = 1; j <arr.length-i; j++) { 

      if(arr[j-1]>arr[j]) { 
       int temp = arr[j-1]; 
       arr[j-1] = arr[j]; 
       arr[j] = temp; 
      } 

     } 
    } 

    System.out.println(Arrays.toString(arr)); 
} 
Problemi correlati