簡體   English   中英

使用遞歸查找數組中第k個最小的元素?

[英]Finding the kth smallest element in an array using recursion?

#include <iostream>

using namespace std;

void moveToKthSmallest(int a[], int size, int k); 


int main() {

int theArray[17] = {42, 5, 412, 56, 14, 98, 488, 4882, 24, 4, 9, 67, 9424, 2, 1, 3, 5};
int num;

cout << "Move to the kth smallest number in the array (size of 17): " << endl;
cin >> num;
moveToKthSmallest(theArray, 17, num);


return 0;
}

void moveToKthSmallest(int a[], int size, int k) {
int pivot = size / 2;
int pivotValue = a[pivot];
int index1 = 0, index2 = 0;
int s1[size], s2[size]; //not sure about this


for (int i = 0; i < size; i++) {
    if (a[i] < pivotValue) {
        s1[index1] = a[i];
        index1++;
    }
    else {
        s2[index2] = a[i];
        index2++; 
    }
}

int s1Size = index1; //problem?
int s2Size = index2; //problem?

if (s1Size == k - 1) {
    cout << pivotValue;
}

else if (s1Size > (k - 1)) {
    moveToKthSmallest(s1, s1Size, k);
}

else if (s1Size < (k - 1)) {
    moveToKthSmallest(s2, s2Size, k - (s1Size - 1));
}
}

我要求用戶輸入一個數字(大於等於0或小於等於17),並且程序應在已生成的數組中輸出第k個最小的數字。

以上是我的嘗試,但是每次運行都會崩潰。 我認為這與函數中數組s1和s2的聲明以及從index1和index2生成的大小值有關。 我嘗試使用向量和動態數組,但在編譯器中不斷收到錯誤消息,例如“錯誤:無法將參數'1'的'std :: vector **'轉換為'int *'到'void moveToKthSmallest'..老實說,我不太確定那是什么意思。

我在這里錯過明顯的東西嗎?

第一步是將其標記為C ++而不是C。因此,您應該使用簡單的std::vector<int>來代替int a[]int size

現在,在您的示例中,每次進行遞歸操作時,您都要遍歷整個數組。

第二點,我不明白為什么這里甚至需要遞歸。 只需在數組上進行一次迭代即可找到答案。

最簡單的方法是使用第二個數組,假設std::vector<int> smallest ,然后對std::vector<int> a一次迭代。

遍歷每個元素時:

  • 如果smallest.size()是已經k ,和電流值是比過去的值大smallest ,然后進行到下一個值a ,否則在除去最后的值smallest

  • 在這一點上, smallest.size()總是小於k ,因此在添加的電流值asmallest在其保持的方式smallest按排序順序排列。

在迭代結束時, smallest向量中的最后一個值是原始向量中的第k個最小值。

如果您想知道第k個最小值的位置,這只是對上述算法的較小修改,方法是跟蹤smallest矢量中的位置而不是值。

這似乎是一個更簡單,直接的解決方案,然后是一個復雜的基於遞歸的方法,並且具有令人困惑的樞軸操作。 同樣,您的樞軸示例需要修改原始數組,而我的方法不需要修改,並且甚至可以與const std::vector<int>

PS不一定要保持smallest的排序順序。 對該算法稍加修改, smallest就可以保持未排序狀態。 此處的作業分配是調整此算法,以使其不需要smallest即可保持排序順序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM