Sort an array in Java

2018-12-31 12:00发布

问题:

I\'m trying to make a program that consists of an array of 10 integers which all has a random value, so far so good.

However, now I need to sort them in order from lowest to highest value and then print it onto the screen, how would I go about doing so?

(Sorry for having so much code for a program that small, I ain\'t that good with loops, just started working with 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] );        

}

回答1:

Loops are also very useful to learn about, esp When using arrays,

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


回答2:

Add the Line before println and your array gets sorted

Arrays.sort( array );


回答3:

It may help you understand loops by implementing yourself. See Bubble sort is easy to understand:

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

Of course, you should not use it in production as there are better performing algorithms for large lists such as QuickSort or MergeSort which are implemented by Arrays.sort(array)



回答4:

Take a look at Arrays.sort()



回答5:

I was lazy and added the loops

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

Your array has a length of 10. You need one variable (i) which takes the values from 0to 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 );

Is a library methods that sorts arrays.



回答6:

Arrays.sort(yourArray)

will do the job perfectly



回答7:

See below, it will give you sorted ascending and descending both

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

Output will be

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 

Note: You can use Math.ranodm instead of adding manual numbers. Let me know if I need to change the code...

Good Luck... Cheers!!!



回答8:

Here is how to use this in your program:

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

}


回答9:

just FYI, you can now use Java 8 new API for sorting any type of array using parallelSort

parallelSort uses Fork/Join framework introduced in Java 7 to assign the sorting tasks to multiple threads available in the thread pool.

the two methods that can be used to sort int array,

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


回答10:

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


回答11:

You can sort a int array with Arrays.sort( array ).



回答12:

For natural order : Arrays.sort(array)

For reverse Order : Arrays.sort(array, Collections.reverseOrder()); -- > It is a static method in Collections class which will further call an inner class of itself to return a reverse Comparator.



回答13:

MOST EFFECTIVE WAY!

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+\" \");
}


回答14:

Java 8 provides the option of using streams which can be used to sort int[] array as:

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

As mentioned in doc for parallelSort :

The sorting algorithm is a parallel sort-merge that breaks the array into sub-arrays that are themselves sorted and then merged. When the sub-array length reaches a minimum granularity, the sub-array is sorted using the appropriate Arrays.sort method. If the length of the specified array is less than the minimum granularity, then it is sorted using the appropriate Arrays.sort method. The algorithm requires a working space no greater than the size of the original array. The ForkJoin common pool is used to execute any parallel tasks.

So if the input array is less than granularity (8192 elements in Java 9 and 4096 in Java 8 I believe), then parallelSort simply calls sequential sort algorithm.

Just in case we want to reverse sort the integer array we can make use of comparator as:

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

Since Java has no way to sort primitives with custom comparator, we have to use intermediate boxing or some other third party library which implements such primitive sorting.



回答15:

You may use Arrays.sort() function.

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


标签: java arrays