#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個最小數字。使用遞歸在數組中尋找第k個最小的元素?
以上是我的嘗試,但每次運行它都會崩潰。我認爲這與函數中的數組s1和s2的聲明以及從index1和index2生成的大小值有關。我試過使用向量和動態數組,但我一直在我的編譯器中收到錯誤消息,例如「錯誤:不能將'std :: vector **'轉換爲'int *'作爲參數'1'到'void moveToKthSmallest」。說實話,我不太清楚這意味着什麼。
我在這裏錯過了一些明顯的東西嗎?