有效地(迭代)找到数组中第k个最小元素的索引?

时间:2015-08-30 10:15:01

标签: java algorithm median

我想在数组中找到第k个最小元素,但实际上需要我的分区方法的索引。

我在这个博客上发现了这个代码,用于查找第k个最小元素: http://blog.teamleadnet.com/2012/07/quick-select-algorithm-find-kth-element.html

但这只返回值,而不是索引。

你知道如何有效地找到它的索引吗?

1 个答案:

答案 0 :(得分:1)

最简单的方法是创建一个长度相同的indices数组,用0length-1的数字填充,当arr数组更改时,执行与indices数组相同的更改。最后返回indices数组中的相应条目。您甚至不必理解原始算法来执行此操作。这是修改后的方法(我的更改标有***):

public static int selectKthIndex(int[] arr, int k) {
    if (arr == null || arr.length <= k)
        throw new IllegalArgumentException();

    int from = 0, to = arr.length - 1;

    // ***ADDED: create and fill indices array
    int[] indices = new int[arr.length];
    for (int i = 0; i < indices.length; i++)
        indices[i] = i;

    // if from == to we reached the kth element
    while (from < to) {
        int r = from, w = to;
        int mid = arr[(r + w) / 2];

        // stop if the reader and writer meets
        while (r < w) {

            if (arr[r] >= mid) { // put the large values at the end
                int tmp = arr[w];
                arr[w] = arr[r];
                arr[r] = tmp;
                // *** ADDED: here's the only place where arr is changed
                // change indices array in the same way
                tmp = indices[w];
                indices[w] = indices[r];
                indices[r] = tmp;
                w--;
            } else { // the value is smaller than the pivot, skip
                r++;
            }
        }

        // if we stepped up (r++) we need to step one down
        if (arr[r] > mid)
            r--;

        // the r pointer is on the end of the first k elements
        if (k <= r) {
            to = r;
        } else {
            from = r + 1;
        }
    }

    // *** CHANGED: return indices[k] instead of arr[k]
    return indices[k];
}

请注意,此方法会修改原始arr数组。如果您不喜欢这样,请在方法的开头添加arr = arr.clone()