Sort an array in Java

后端 未结 17 977
傲寒
傲寒 2020-11-22 04:53

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 l

相关标签:
17条回答
  • 2020-11-22 05:21

    We can also use binary search tree for getting sorted array by using in-order traversal method. The code also has implementation of basic binary search tree below.

    class Util {
        public static void printInorder(Node node) 
        { 
            if (node == null) {
                return;
            } 
    
            /* traverse left child */
            printInorder(node.left); 
    
            System.out.print(node.data + " "); 
    
            /* traverse right child */
            printInorder(node.right); 
         } 
    
        public static void sort(ArrayList<Integer> al, Node node) {
            if (node == null) {
                return;
            } 
    
            /* sort left child */
            sort(al, node.left); 
    
            al.add(node.data);
    
            /* sort right child */
            sort(al, node.right); 
    
        }
    }
    
    class Node {
        Node left;
        Integer data;
        Node right;
    
        public Node(Integer data) {
            this.data = data;
        }
    
        public void insert(Integer element) {
            if(element.equals(data)) {
                return;
            }
    
            // if element is less than current then we know we will insert element to left-sub-tree
            if(element < data) {
                // if this node does not have a sub tree then this is the place we insert the element.
                if(this.left == null) {
                    this.left = new Node(element);  
                } else { // if it has left subtree then we should iterate again.
                    this.left.insert(element);
                }
            } else {
                if(this.right == null) {
                    this.right = new Node(element);
                } else {
                    this.right.insert(element);
                }
            }
        }
    }
    
    class Tree {
        Node root;
    
        public void insert(Integer element) {
            if(root == null) {
                root = new Node(element);
            } else {
                root.insert(element);
            }       
        }
    
        public void print() {
            Util.printInorder(root);
        }
    
        public ArrayList<Integer> sort() {
            ArrayList<Integer> al = new ArrayList<Integer>();
            Util.sort(al, root);
            return al;
        }
    }
    
    public class Test {
    
        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));
    
            Tree tree = new Tree();
    
            for (int i = 0; i < array.length; i++) {
                tree.insert(array[i]);
            }
    
            tree.print();
    
            ArrayList<Integer> al = tree.sort();    
    
            System.out.println("sorted array : ");
            al.forEach(item -> System.out.print(item + " "));
    }
    

    }

    0 讨论(0)
  • 2020-11-22 05:24

    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();
    
    0 讨论(0)
  • 2020-11-22 05:27

    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.

    0 讨论(0)
  • 2020-11-22 05:30

    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] );        
    
    }
    
    0 讨论(0)
  • 2020-11-22 05:31
    Arrays.sort(yourArray)
    

    will do the job perfectly

    0 讨论(0)
  • 2020-11-22 05:32

    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.

    0 讨论(0)
提交回复
热议问题