Java 如何从int数组中获取多个最小值?

Java 如何从int数组中获取多个最小值?,java,Java,我试图从一个int数组中获得至少5个最小值。我的代码附加工作,但它跳过几个值 public static void main(String[] args) { int array[] = {0, 1, 2, 1, 4, 5, 1, 7, 8, 1, 10, 11, 12, 13, 1, 15, 16, 17, 18, 19, 20, 2, 22, 23}; int min = 0; int index = 0; String output = ""; fo

我试图从一个int数组中获得至少5个最小值。我的代码附加工作,但它跳过几个值

public static void main(String[] args) {
    int array[] = {0, 1, 2, 1, 4, 5, 1, 7, 8, 1, 10, 11, 12, 13, 1, 15, 16, 17, 18, 19, 20, 2, 22, 23};
    int min = 0;
    int index = 0;
    String output = "";
    for (int x = 0; x < 5; x++){
        min = array[x];
        index++;
        for(int i = index, limit = array.length; i < limit; ++i){
            if(array[i] <= min){
                min = array[i];
                index = i + 1;
                break;
            }
        }
        output += index + "\t";               
    }
    System.out.println(output);
}
如果不想对传入的数组进行变异,即不想对其进行排序,请先添加以下行:

int[] array = Arrays.copyOf(array);

也许可以使用Arrays.sort对数组进行排序,然后取前五个值:

Arrays.sort(array);

现在数组[0]到数组[4]包含最低的5个值。

如果您只想得到5个最小值,我同意Bohemian的回答。 如果你想显示数组的位置,比如1,2,4,7,10,你的演示是跳过2, 试试我的测试

public static void main(String[] args) {
    int getNum = 5;
    int step = 0;
    String output = "";
    int array[] = {0, 1, 2, 1, 4, 5, 1, 7, 8, 1, 10, 11, 12, 13, 1, 15, 16, 17, 18, 19, 20, 2, 22, 23};
    int arrayClone[] = array.clone();
    Arrays.sort(array);
    int arrayResult[] = Arrays.copyOfRange(array, 0, getNum); //the arrayResult is what you want minimum values

    ploop:for (int i:arrayResult) {
        int index = 1;
        for (int j :arrayClone) {
            if(j==i){
                step++;
                output += index + "\t"; 
                if (step>=getNum) {
                    break ploop;
                }                    
            }
            index++;
        }
    }  

    System.out.println(output);        
}

允许您先对数组进行排序吗?您是否在寻找重复的最小值?@AlexandreP.Levasseur问题在标题中。是的,我们也需要重复的最小值
public static void main(String[] args) {
    int getNum = 5;
    int step = 0;
    String output = "";
    int array[] = {0, 1, 2, 1, 4, 5, 1, 7, 8, 1, 10, 11, 12, 13, 1, 15, 16, 17, 18, 19, 20, 2, 22, 23};
    int arrayClone[] = array.clone();
    Arrays.sort(array);
    int arrayResult[] = Arrays.copyOfRange(array, 0, getNum); //the arrayResult is what you want minimum values

    ploop:for (int i:arrayResult) {
        int index = 1;
        for (int j :arrayClone) {
            if(j==i){
                step++;
                output += index + "\t"; 
                if (step>=getNum) {
                    break ploop;
                }                    
            }
            index++;
        }
    }  

    System.out.println(output);        
}