Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中对数组排序_Java_Arrays - Fatal编程技术网

在Java中对数组排序

在Java中对数组排序,java,arrays,Java,Arrays,我正在尝试制作一个由10个整数组成的数组组成的程序,所有这些整数都有一个随机值,到目前为止还不错 sort() method is a java.util.Arrays class method. Declaration : Arrays.sort(arrName) 但是,现在我需要按照从最低到最高的顺序对它们进行排序,然后将其打印到屏幕上,我将如何进行呢 sort() method is a java.util.Arrays class method.

我正在尝试制作一个由10个整数组成的数组组成的程序,所有这些整数都有一个随机值,到目前为止还不错

sort() method is a java.util.Arrays class method.          
Declaration : Arrays.sort(arrName)
但是,现在我需要按照从最低到最高的顺序对它们进行排序,然后将其打印到屏幕上,我将如何进行呢

sort() method is a java.util.Arrays class method.          
Declaration : Arrays.sort(arrName)
(很抱歉为这么小的程序编写了这么多代码,我不太擅长循环,刚开始使用Java)

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

查看您可以使用
数组对int数组进行排序。排序(数组)

在println之前添加该行,然后对数组进行排序

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

它可以通过自己实现来帮助您理解循环。请参见气泡排序易于理解:

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;
            }
        }
    }
}
sort() method is a java.util.Arrays class method.          
Declaration : Arrays.sort(arrName)
public void bubbleSort(int[]数组){
布尔交换=真;
int j=0;
int tmp;
while(交换){
交换=假;
j++;
对于(int i=0;i数组[i+1]){
tmp=阵列[i];
数组[i]=数组[i+1];
数组[i+1]=tmp;
交换=真;
}
}
}
}

当然,您不应该在生产中使用它,因为对于大型列表,有性能更好的算法,例如快速排序合并排序,它们是由
数组实现的。排序(数组)
我很懒,添加了循环

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]);
        }
    }
}
sort() method is a java.util.Arrays class method.          
Declaration : Arrays.sort(arrName)

是一个对数组进行排序的库方法。

循环也非常有用,特别是在使用数组时

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();
sort() method is a java.util.Arrays class method.          
Declaration : Arrays.sort(arrName)
int[]数组=新的int[10];
Random rand=新的Random();
for(int i=0;i=0;i--)
System.out.print(数组[i]+“”);
System.out.println();

以下是如何在程序中使用此选项:

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

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

如下所示,它将为您提供升序和降序排序

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();
}}
sort() method is a java.util.Arrays class method.          
Declaration : Arrays.sort(arrName)
输出将是

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 
sort() method is a java.util.Arrays class method.          
Declaration : Arrays.sort(arrName)
注意:您可以使用Math.ranodm而不是手动添加数字。如果我需要更改代码,请告诉我

sort() method is a java.util.Arrays class method.          
Declaration : Arrays.sort(arrName)
祝你好运。。。干杯

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

将完美地完成这项工作

仅供参考,您现在可以使用Java 8新API使用
并行排序

sort() method is a java.util.Arrays class method.          
Declaration : Arrays.sort(arrName)
parallelSort
使用Java 7中引入的Fork/Join框架将排序任务分配给线程池中可用的多个线程

sort() method is a java.util.Arrays class method.          
Declaration : Arrays.sort(arrName)
可用于排序
int
数组的两种方法

parallelSort(int[] a)
parallelSort(int[] a,int fromIndex,int toIndex)
sort() method is a java.util.Arrays class method.          
Declaration : Arrays.sort(arrName)
最有效的方法

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+" ");
}
sort() method is a java.util.Arrays class method.          
Declaration : Arrays.sort(arrName)
int[]数组={2,3,4,5,3,4,2,34,2,56,98,32,54};
for(int i=0;i
对于自然顺序:
数组。排序(数组)

sort() method is a java.util.Arrays class method.          
Declaration : Arrays.sort(arrName)
对于反向顺序:
Arrays.sort(array,Collections.reverseOrder())-->它是Collections类中的静态方法,它将进一步调用自身的内部类以返回反向比较器。

您可以使用函数

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

Java 8提供了使用流的选项,可将
int[]数组排序为:

sort() method is a java.util.Arrays class method.          
Declaration : Arrays.sort(arrName)
int[] sorted = Arrays.stream(array).sorted().toArray(); // option 1
Arrays.parallelSort(array); //option 2
并行排序
中所述:

sort() method is a java.util.Arrays class method.          
Declaration : Arrays.sort(arrName)
排序算法是打破数组的并行排序合并 放入子数组中,这些子数组本身进行排序,然后合并。当 子数组长度达到最小粒度时,子数组为 使用适当的Arrays.sort方法进行排序。如果 指定的数组小于最小粒度,则为 使用适当的Arrays.sort方法进行排序。算法 需要的工作空间不大于原始文件的大小 数组。ForkJoin公共池用于执行任何并行任务

sort() method is a java.util.Arrays class method.          
Declaration : Arrays.sort(arrName)
因此,如果输入数组小于粒度(我相信Java9中有8192个元素,Java8中有4096个元素),那么
parallelSort
只调用顺序排序算法

sort() method is a java.util.Arrays class method.          
Declaration : Arrays.sort(arrName)
为了防止我们想要对整数数组进行反向排序,我们可以使用比较器:

sort() method is a java.util.Arrays class method.          
Declaration : Arrays.sort(arrName)
int[] reverseSorted = IntStream.of(array).boxed()
                        .sorted(Comparator.reverseOrder()).mapToInt(i -> i).toArray();

由于Java无法使用自定义比较器对原语进行排序,因此我们必须使用中间装箱或其他实现此类原语排序的第三方库。

如果您想自己构建快速排序算法并更了解其工作原理,请检查以下代码:

sort() method is a java.util.Arrays class method.          
Declaration : Arrays.sort(arrName)
1-创建排序类

sort() method is a java.util.Arrays class method.          
Declaration : Arrays.sort(arrName)
class QuickSort {
    private int input[];
    private int length;

    public void sort(int[] numbers) {
        if (numbers == null || numbers.length == 0) {
            return;
        }
        this.input = numbers;
        length = numbers.length;
        quickSort(0, length - 1);
    }
    /*
     * This method implements in-place quicksort algorithm recursively.
     */

    private void quickSort(int low, int high) {
        int i = low;
        int j = high;

        // pivot is middle index
        int pivot = input[low + (high - low) / 2];

        // Divide into two arrays
        while (i <= j) {
            /**
             * As shown in above image, In each iteration, we will identify a
             * number from left side which is greater then the pivot value, and
             * a number from right side which is less then the pivot value. Once
             * search is complete, we can swap both numbers.
             */
            while (input[i] < pivot) {
                i++;
            }
            while (input[j] > pivot) {
                j--;
            }
            if (i <= j) {
                swap(i, j);
                // move index to next position on both sides
                i++;
                j--;
            }
        }

        // calls quickSort() method recursively
        if (low < j) {
            quickSort(low, j);
        }

        if (i < high) {
            quickSort(i, high);
        }
    }

    private void swap(int i, int j) {
        int temp = input[i];
        input[i] = input[j];
        input[j] = temp;
    }
}
3-输出

sort() method is a java.util.Arrays class method.          
Declaration : Arrays.sort(arrName)
Unsorted array :[6, 5, 3, 1, 8, 7, 2, 4] 
Sorted array :[1, 2, 3, 4, 5, 6, 7, 8]

我们还可以使用二叉搜索树通过顺序遍历方法获得排序数组。下面的代码还实现了基本的二进制搜索树

sort() method is a java.util.Arrays class method.          
Declaration : Arrays.sort(arrName)
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 + " "));
}
class-Util{
公共静态无效打印顺序(节点)
{ 
if(node==null){
返回;
} 
/*左遍历子对象*/
printInorder(node.left);
System.out.print(node.data+“”);
/*遍历右子对象*/
printInorder(node.right);
} 
公共静态无效排序(ArrayList al,Node){
if(node==null){
返回;
} 
/*排序左撇子*/
排序(al,节点。左);
al.add(节点数据);
/*正确的孩子*/
排序(al,node.right);
}
}
类节点{
左淋巴结;
整数数据;
节点权;
公共节点(整数数据){
这个数据=数据;
}
公共void插入(整数元素){
if(元素等于(数据)){
返回;
}
//若元素小于当前值,那个么我们知道将把元素插入到左子树中
if(元素<数据){
//如果此节点没有子树,则这是插入元素的位置。
if(this.left==null){
this.left=新节点(元素);
}否则{//如果它离开了子树,那么我们应该再次迭代。
这个。左。inse