C++快速排序向量并保留原始索引号

C++ QuickSorting a vector and keeping the original index numbers

本文关键字:原始 索引 保留 快速排序 向量 C++      更新时间:2023-10-16

我有一个有效的快速排序函数,但我不确定如何保留未排序数据的原始索引号。有什么想法吗?谢谢!这是我的函数。我可以以某种方式将一对合并在那里吗?

double NearestNeighbor::partition(vector<double>& theList, double start, double end) {
int pivot = theList[end];
int bottom = start - 1;
int top = end;
bool notdone = true;
while (notdone) {
    while (notdone) {
        bottom += 1;
        if (bottom == top) {
            notdone = false;
            break;
        }
        if (theList[bottom] > pivot) {
            theList[top] = theList[bottom];
            break;
        }
    }
    while (notdone) {
        top = top - 1;
        if (top == bottom) {
            notdone = false;
            break;
        }
        if (theList[top] < pivot) {
            theList[bottom] = theList[top];
            break;
        }
    }
}
theList[top] = pivot;
return top;

}

快速排序函数

double NearestNeighbor::quickSort(vector<double>& theList, double start, double end) {
if (start < end) {
    double split = partition(theList, start, end); //recursion   
    quickSort(theList, start, split - 1);
    quickSort(theList, split + 1, end);
} else {
    return 0;
}
}

我已经计算了几个向量的点积,我正在尝试打印 10 个最近的邻居。我可以对它们进行排序,但我的教授被要求返回 10 个最近邻居的索引号,所以我试图弄清楚如何保留这些原始索引号。

例如:排序后的数据可能如下所示:

索引号:3 45 15 9 45
数据: 10 14 17 30 35

我只想打印出索引号。抱歉,我不知道如何格式化它,以便数字与数据对齐,但我想你明白了。

  1. std::vector<T>转换为 std::vector<std::pair<int, T>>
  2. 使用pair中的第二个对std::vector<std::pair<int, T>>进行排序。