c++ 快速选择算法

ct3nt3jp  于 2023-08-09  发布在  其他
关注(0)|答案(2)|浏览(119)

我正在尝试在一个随机生成数字的数组上实现快速选择算法。现在在编码算法之后,它不会从最低到最高对数组进行排序,也无法找到第 k 个最小元素。

#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;

int Partition(int *myArray, int startingIndex, int endingIndex){
    int pivot = myArray[endingIndex];
    int partitionIndex = startingIndex;
    for(int i = startingIndex; i<endingIndex; i++){
        if(myArray[i]<= pivot){
            swap(myArray[i],myArray[partitionIndex]);
            partitionIndex++;
        }
    }
    swap(myArray[partitionIndex],myArray[endingIndex]);
    return partitionIndex;
} 
 
int QuickSelect(int *myArray, int startingIndex, int endingIndex, int KthElement){
    if (startingIndex < endingIndex){
        int partitionIndex = Partition(myArray, startingIndex, endingIndex);
        if(KthElement == partitionIndex)
            return KthElement;
        if(KthElement < partitionIndex)
            QuickSelect(myArray, startingIndex, partitionIndex - 1, KthElement);
        else
            QuickSelect(myArray, partitionIndex + 1, endingIndex, KthElement);
    }
}
    /*if(startingIndex < endingIndex){
        int partitionIndex = Partition(myArray, startingIndex,endingIndex);
        QuickSelect(myArray,startingIndex,partitionIndex-1);
        QuickSelect(myArray,partitionIndex+1,endingIndex);
    }// 1 */

void printArray(string intro, int const *myArray, int n, ostream &out) {
    out << intro;
    for(int i = 0; i < n; i++){
        out << " " << myArray[i];
    }
    out << endl;
}

int main(){
    int numOfElements;
    int KthElement;
    srand(time(NULL));
    cout<<"Enter The Amount Of Numbers You Wish To Use: ";
    cin >> numOfElements;
    int myArray[numOfElements];

    for(int i = 0; i< numOfElements; i++){
        myArray[i] = rand() %10;
    }

    printArray("Array Before Sorting:", myArray, numOfElements, cout);

    cout <<"\nEnter The Rank K Of The Element You Wish To Retrieve: ";
    cin >> KthElement;

    QuickSelect(myArray,0,numOfElements,KthElement);

    printArray("Array After Sorting:", myArray, numOfElements, cout);

    cout << "The " << KthElement << " Smallest Element Is: "
         << QuickSelect(myArray,0,numOfElements,KthElement);
}

字符串

pqwbnv8z

pqwbnv8z1#

如果numOfElements为5,则array从0扩展到4。你的endingIndex假设它是数组的最后一个索引。
修正:

QuickSelect(myArray, 0,numOfElements-1,KthElement);

字符串
代码的问题:

  • 中的越界数组位置
int pivot = myArray[endingIndex];

  • 检查k<1k>(num_of_elements)
  • 检查你的代码num_of_elements = 1。
  • 检查k对数组的意义,即对于k=1,应该返回arr[0]而不是arr[1];
5tmbdcev

5tmbdcev2#

int QuickSelect()的问题:
·未记录-它返回什么,为什么是KthElement而不是k
·不总是返回值
·当它 * 确实 * 返回一个值时,它总是其最后一个参数的未修改值

相关问题