在不进行排序的情况下查找数组中n个最小值的索引

Find the index of the n-least values in a array without sorting

本文关键字:索引 最小值 数组 情况下 排序 查找      更新时间:2023-10-16

我有以下数组:

{7, 1, 3, 9, 5, 4, 7, 8, 2}

以及空的n尺寸阵列。现在,我想在不排序的情况下找到给定数组中n个最小值的索引,并将它们写入空数组。例如n=3:

{1, 8, 2}

有简单的方法吗?

如果不限制对其他数组进行排序,则创建一个索引数组,并根据原始数组对索引数组进行排序。

#include <vector>
#include <iostream>
#include <algorithm>
#include <numeric>
int main()
{
int n = 3;
// test data
std::vector<int> test = { 7, 1, 3, 9, 5, 4, 7, 8, 2 };
// index array
std::vector<int> index(test.size());
// set the index array to 0, 1, 2, … n-1
std::iota(index.begin(), index.end(), 0);
// sort the index array
std::sort(index.begin(), index.end(), [&](int n1, int n2) { return test[n1] < test[n2]; });
// output results -- note we are printing the index array
for (int i = 0; i < n; ++i)
std::cout << index[i] << "n";
}

输出:

1
8 
2

从数组中的第一个值开始。

将数组中的值与n-least数组中索引的值进行比较。(如果为空,则添加它(。

如果该值较小,则将数组从该位置偏移,并将索引添加到n-least数组中的该位置。

如果不小于,则比较来自n-least数组的下一个值,依此类推。

这可能不是最优的,但至少它不是一个简单的解决方案所能产生的O(n^2(复杂性。

我会用伪代码写这个:

n = 3
arr = [7, 1, 3, 9, 5, 4, 7, 8, 2]
narr = []
for i as 0 to sizeof(arr) - 1
for j as 0 to n - 1
if narr[j] is undefined or arr[i] < arr[narr[j]]
narr.shiftRight(j, 1)
narr[j] = i;
break
endif
endfor
endfor