gpt4 book ai didi

c++ - 快速选择算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:58:43 24 4
gpt4 key购买 nike

我正在尝试在具有随机生成数字的数组上实现快速选择算法。现在在用代码编写算法后,它不会从最低到最高对数组进行排序,也无法找到第 k 个最小的元素。我会很感激我得到的帮助。谢谢。

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

void printArray(int *myArray, int n){
for(int i = 0; i < n; i++){
cout << myArray[i] << " ";
}
}

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);
QuickSelect(myArray,startingIndex,partitionIndex-1);
QuickSelect(myArray,partitionIndex+1,endingIndex);
}*/1
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);
}
}
int main(){

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

cout << "Array Before Sorting: ";
for(int i = 0; i< numOfElements; i++){
myArray[i] = rand() %10;
}

printArray(myArray, numOfElements);

cout << endl;
cout << endl;

cout <<"Enter The Index Of The Kth Element You Wish To Retrieve: ";
cin >> KthElement;

QuickSelect(myArray, 0,numOfElements,KthElement);
cout << "Array After Sorting: ";
printArray(myArray, numOfElements);
cout << endl;

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

}

最佳答案

对于 numOfElements作为 5,数组从 0 扩展到 4。你的endingIndex假定它是数组的最后一个索引。

修复:

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

你的代码有问题:

  • 您的程序访问了

    中的边界数组位置
    int pivot = myArray[endingIndex];
  • 检查 k<1k>(num_of_elements) .

  • 同时检查您的代码是否有 num_of_elements = 1。

  • 检查 k 对数组的意义,即 For k=1 , arr[0]不应该退回 arr[1] ;

关于c++ - 快速选择算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27814143/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com