简体   繁体   中英

How would I find the index of the smallest value in an int array?

我对java还是很陌生,所以我想保持简单,我想我必须采用数组的第一个值,然后将其与每个后续值进行比较,如果该值大于第一个值,则替换价值,但我不知道如何从中获取索引。

For an unstructured, unsorted array the best you can do, assuming you are only going to find the minimum value once, is a simple iteration over all elements ( O(n) complexity), like so:

public int findMinIdx(int[] numbers) {
    if (numbers == null || numbers.length == 0) return -1; // Saves time for empty array
    // As pointed out by ZouZou, you can save an iteration by assuming the first index is the smallest
    int minVal = numbers[0] // Keeps a running count of the smallest value so far
    int minIdx = 0; // Will store the index of minVal
    for(int idx=1; idx<numbers.length; idx++) {
        if(numbers[idx] < minVal) {
            minVal = numbers[idx];
            minIdx = idx;
        }
    }
    return minIdx;
}

Also, in the case of a tie for minimum value, this method will return the index of the first case of that value it found. If you want it to be the last case, simply change numbers[idx] < minVal to numbers[idx] <= minVal .

Here is with Java 8

 public static int findMinIdx(int[] numbers) {
        OptionalInt minimun = IntStream.of(numbers).min();
        return   IntStream.of(numbers).boxed().collect(toList()).indexOf(minimun.getAsInt());
    }

Never cared about run time optimization, was just looking for a solution!, this worked and this would help you too, finding the index of the lowest values in an array.

    // array[] -> Received the array in question as an parameter
    // index -> stores the index of the lowest value
    // in for loop, i is important to complete all the comparison in the function
    // When it finds a lower value between the two, it does not change the index
    // When it finds a lower value it changes it's index to that index
    // If array has same value more than once, it will provide index to that values last occurrence
    // Correct me if you find anything not working in this example...
    //...

private static int index_of_minimum_value(int[] array) {
    int index = 0;
    for (int i = 1; i < array.length; i++) {
        if ((array[i - 1] < array[i]) && ([index] > array[i - 1])) index = i - 1;
        else if (array[index] > array[i]) index = i;
    }
    return index;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM