我有一个包含 N 个数字的向量,我想在数组中找到第 n 个数字。我正在使用快速排序的变体,但有时会遇到无限循环的问题,我认为如果最大的数字是两个数组中的唯一选项。一个数字可以在数组中出现多次,例如,如果我为 N 选择 10 并且我想找到第一个最大的数字,我可能会在左侧数组中以 {9,9} 结束,从而导致无限循环。我能做些什么来解决这个问题?这是我的代码。
#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <vector>
using namespace std;
int partition(int n, int arrsize, vector<int> intarr); //pass vector by val
int main() {
int n, N;
cout << "Please enter n: " << endl;
cin >> n;
cout << "Please enter N: " << endl;
cin >> N;
vector<int> array;
srand(time(NULL));
for(i=0; i < N; i++) {
array.push_back(1 + rand() % N);
cout << array.at(i) << ", ";
}
//Get the nth largest value of array[N]
int arraylen = array.size();
cout << "\nArraylen is " << arraylen << endl;
int result = partition(n, arraylen, array);
cout << "The " << n << "th largest number is: " << result <<endl;
return 0;
}
int partition(int n, int arrsize, vector<int> intarr) {
//1. Get a random value from the array:
int random = rand() % arrsize;
int pivot = intarr.at(random);
//2. Partition the array into 2 halves left < pivot > right
vector<int> left;
vector<int> right;
for(int j=0; j < arrsize; j++) {
if (intarr[j] >= pivot)
left.push_back(intarr[j]);
else if (intarr.at(j) < pivot)
right.push_back(intarr[j]);
else continue;
}
cout << "\n \n" << "Left = ";
for(int k = 0; k < left.size(); k++) {
cout << left.at(k) << ", ";
}
cout << endl << "Right = ";
for(int k = 0; k < right.size(); k++) {
cout << right.at(k) << ", ";
}
int leftlen = left.size();
int rightlen = right.size();
if (n < leftlen)
return partition(n, leftlen, left);
else if (n > (arrsize - rightlen)) {
n = n - (leftlen);
return partition(n, rightlen, right);
}
else return pivot;
}