快速选择算法

时间:2015-01-07 07:07:44

标签: c++ algorithm quickselect

我试图在随机生成数字的数组上实现快速选择算法。现在在代码中编写算法之后,它不会将数组从最低到最高排序,也无法找到第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);

}

1 个答案:

答案 0 :(得分:2)

对于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对数组的含义,即对于k=1arr[0]不应返回arr[1];